babylon.max.js 3.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342
  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 = [];
  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 = [];
  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 = [];
  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 = [];
  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. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. 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);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * 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.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. 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)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. 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;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. 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)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * 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.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * 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).
  5332. * 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.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable() {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. }
  5339. /**
  5340. * Create a new Observer with the specified callback
  5341. * @param callback the callback that will be executed for that Observer
  5342. * @param mask the mask used to filter observers
  5343. * @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.
  5344. */
  5345. Observable.prototype.add = function (callback, mask, insertFirst) {
  5346. if (mask === void 0) { mask = -1; }
  5347. if (insertFirst === void 0) { insertFirst = false; }
  5348. if (!callback) {
  5349. return null;
  5350. }
  5351. var observer = new Observer(callback, mask);
  5352. if (insertFirst) {
  5353. this._observers.unshift(observer);
  5354. }
  5355. else {
  5356. this._observers.push(observer);
  5357. }
  5358. return observer;
  5359. };
  5360. /**
  5361. * Remove an Observer from the Observable object
  5362. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5363. */
  5364. Observable.prototype.remove = function (observer) {
  5365. var index = this._observers.indexOf(observer);
  5366. if (index !== -1) {
  5367. this._observers.splice(index, 1);
  5368. return true;
  5369. }
  5370. return false;
  5371. };
  5372. /**
  5373. * Remove a callback from the Observable object
  5374. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5375. */
  5376. Observable.prototype.removeCallback = function (callback) {
  5377. for (var index = 0; index < this._observers.length; index++) {
  5378. if (this._observers[index].callback === callback) {
  5379. this._observers.splice(index, 1);
  5380. return true;
  5381. }
  5382. }
  5383. return false;
  5384. };
  5385. /**
  5386. * Notify all Observers by calling their respective callback with the given data
  5387. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5388. * @param eventData
  5389. * @param mask
  5390. */
  5391. Observable.prototype.notifyObservers = function (eventData, mask) {
  5392. if (mask === void 0) { mask = -1; }
  5393. var state = this._eventState;
  5394. state.mask = mask;
  5395. state.skipNextObservers = false;
  5396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5397. var obs = _a[_i];
  5398. if (obs.mask & mask) {
  5399. obs.callback(eventData, state);
  5400. }
  5401. if (state.skipNextObservers) {
  5402. return false;
  5403. }
  5404. }
  5405. return true;
  5406. };
  5407. /**
  5408. * return true is the Observable has at least one Observer registered
  5409. */
  5410. Observable.prototype.hasObservers = function () {
  5411. return this._observers.length > 0;
  5412. };
  5413. /**
  5414. * Clear the list of observers
  5415. */
  5416. Observable.prototype.clear = function () {
  5417. this._observers = new Array();
  5418. };
  5419. /**
  5420. * Clone the current observable
  5421. */
  5422. Observable.prototype.clone = function () {
  5423. var result = new Observable();
  5424. result._observers = this._observers.slice(0);
  5425. return result;
  5426. };
  5427. /**
  5428. * Does this observable handles observer registered with a given mask
  5429. * @param {number} trigger - the mask to be tested
  5430. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5431. **/
  5432. Observable.prototype.hasSpecificMask = function (mask) {
  5433. if (mask === void 0) { mask = -1; }
  5434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5435. var obs = _a[_i];
  5436. if (obs.mask & mask || obs.mask === mask) {
  5437. return true;
  5438. }
  5439. }
  5440. return false;
  5441. };
  5442. return Observable;
  5443. }());
  5444. BABYLON.Observable = Observable;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.observable.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var SmartArray = (function () {
  5450. function SmartArray(capacity) {
  5451. this.length = 0;
  5452. this._duplicateId = 0;
  5453. this.data = new Array(capacity);
  5454. this._id = SmartArray._GlobalId++;
  5455. }
  5456. SmartArray.prototype.push = function (value) {
  5457. this.data[this.length++] = value;
  5458. if (this.length > this.data.length) {
  5459. this.data.length *= 2;
  5460. }
  5461. if (!value.__smartArrayFlags) {
  5462. value.__smartArrayFlags = {};
  5463. }
  5464. value.__smartArrayFlags[this._id] = this._duplicateId;
  5465. };
  5466. SmartArray.prototype.forEach = function (func) {
  5467. for (var index = 0; index < this.length; index++) {
  5468. func(this.data[index]);
  5469. }
  5470. };
  5471. SmartArray.prototype.pushNoDuplicate = function (value) {
  5472. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5473. return false;
  5474. }
  5475. this.push(value);
  5476. return true;
  5477. };
  5478. SmartArray.prototype.sort = function (compareFn) {
  5479. this.data.sort(compareFn);
  5480. };
  5481. SmartArray.prototype.reset = function () {
  5482. this.length = 0;
  5483. this._duplicateId++;
  5484. };
  5485. SmartArray.prototype.dispose = function () {
  5486. this.reset();
  5487. if (this.data) {
  5488. this.data.length = 0;
  5489. this.data = null;
  5490. }
  5491. };
  5492. SmartArray.prototype.concat = function (array) {
  5493. if (array.length === 0) {
  5494. return;
  5495. }
  5496. if (this.length + array.length > this.data.length) {
  5497. this.data.length = (this.length + array.length) * 2;
  5498. }
  5499. for (var index = 0; index < array.length; index++) {
  5500. this.data[this.length++] = (array.data || array)[index];
  5501. }
  5502. };
  5503. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5504. if (array.length === 0) {
  5505. return;
  5506. }
  5507. if (this.length + array.length > this.data.length) {
  5508. this.data.length = (this.length + array.length) * 2;
  5509. }
  5510. for (var index = 0; index < array.length; index++) {
  5511. var item = (array.data || array)[index];
  5512. this.pushNoDuplicate(item);
  5513. }
  5514. };
  5515. SmartArray.prototype.indexOf = function (value) {
  5516. var position = this.data.indexOf(value);
  5517. if (position >= this.length) {
  5518. return -1;
  5519. }
  5520. return position;
  5521. };
  5522. SmartArray.prototype.contains = function (value) {
  5523. return this.data.indexOf(value) !== -1;
  5524. };
  5525. // Statics
  5526. SmartArray._GlobalId = 0;
  5527. return SmartArray;
  5528. }());
  5529. BABYLON.SmartArray = SmartArray;
  5530. })(BABYLON || (BABYLON = {}));
  5531. //# sourceMappingURL=babylon.smartArray.js.map
  5532. var BABYLON;
  5533. (function (BABYLON) {
  5534. // Screenshots
  5535. var screenshotCanvas;
  5536. var cloneValue = function (source, destinationObject) {
  5537. if (!source)
  5538. return null;
  5539. if (source instanceof BABYLON.Mesh) {
  5540. return null;
  5541. }
  5542. if (source instanceof BABYLON.SubMesh) {
  5543. return source.clone(destinationObject);
  5544. }
  5545. else if (source.clone) {
  5546. return source.clone();
  5547. }
  5548. return null;
  5549. };
  5550. var Tools = (function () {
  5551. function Tools() {
  5552. }
  5553. ;
  5554. /**
  5555. * Interpolates between a and b via alpha
  5556. * @param a The lower value (returned when alpha = 0)
  5557. * @param b The upper value (returned when alpha = 1)
  5558. * @param alpha The interpolation-factor
  5559. * @return The mixed value
  5560. */
  5561. Tools.Mix = function (a, b, alpha) {
  5562. return a * (1 - alpha) + b * alpha;
  5563. };
  5564. Tools.Instantiate = function (className) {
  5565. var arr = className.split(".");
  5566. var fn = (window || this);
  5567. for (var i = 0, len = arr.length; i < len; i++) {
  5568. fn = fn[arr[i]];
  5569. }
  5570. if (typeof fn !== "function") {
  5571. return null;
  5572. }
  5573. return fn;
  5574. };
  5575. Tools.SetImmediate = function (action) {
  5576. if (window.setImmediate) {
  5577. window.setImmediate(action);
  5578. }
  5579. else {
  5580. setTimeout(action, 1);
  5581. }
  5582. };
  5583. Tools.IsExponentOfTwo = function (value) {
  5584. var count = 1;
  5585. do {
  5586. count *= 2;
  5587. } while (count < value);
  5588. return count === value;
  5589. };
  5590. /**
  5591. * Find the next highest power of two.
  5592. * @param x Number to start search from.
  5593. * @return Next highest power of two.
  5594. */
  5595. Tools.CeilingPOT = function (x) {
  5596. x--;
  5597. x |= x >> 1;
  5598. x |= x >> 2;
  5599. x |= x >> 4;
  5600. x |= x >> 8;
  5601. x |= x >> 16;
  5602. x++;
  5603. return x;
  5604. };
  5605. /**
  5606. * Find the next lowest power of two.
  5607. * @param x Number to start search from.
  5608. * @return Next lowest power of two.
  5609. */
  5610. Tools.FloorPOT = function (x) {
  5611. x = x | (x >> 1);
  5612. x = x | (x >> 2);
  5613. x = x | (x >> 4);
  5614. x = x | (x >> 8);
  5615. x = x | (x >> 16);
  5616. return x - (x >> 1);
  5617. };
  5618. /**
  5619. * Find the nearest power of two.
  5620. * @param x Number to start search from.
  5621. * @return Next nearest power of two.
  5622. */
  5623. Tools.NearestPOT = function (x) {
  5624. var c = Tools.CeilingPOT(x);
  5625. var f = Tools.FloorPOT(x);
  5626. return (c - x) > (x - f) ? f : c;
  5627. };
  5628. Tools.GetExponentOfTwo = function (value, max, mode) {
  5629. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5630. var pot;
  5631. switch (mode) {
  5632. case BABYLON.Engine.SCALEMODE_FLOOR:
  5633. pot = Tools.FloorPOT(value);
  5634. break;
  5635. case BABYLON.Engine.SCALEMODE_NEAREST:
  5636. pot = Tools.NearestPOT(value);
  5637. break;
  5638. case BABYLON.Engine.SCALEMODE_CEILING:
  5639. pot = Tools.CeilingPOT(value);
  5640. break;
  5641. }
  5642. return Math.min(pot, max);
  5643. };
  5644. Tools.GetFilename = function (path) {
  5645. var index = path.lastIndexOf("/");
  5646. if (index < 0)
  5647. return path;
  5648. return path.substring(index + 1);
  5649. };
  5650. Tools.GetDOMTextContent = function (element) {
  5651. var result = "";
  5652. var child = element.firstChild;
  5653. while (child) {
  5654. if (child.nodeType === 3) {
  5655. result += child.textContent;
  5656. }
  5657. child = child.nextSibling;
  5658. }
  5659. return result;
  5660. };
  5661. Tools.ToDegrees = function (angle) {
  5662. return angle * 180 / Math.PI;
  5663. };
  5664. Tools.ToRadians = function (angle) {
  5665. return angle * Math.PI / 180;
  5666. };
  5667. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5668. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5669. var output = "";
  5670. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5671. var i = 0;
  5672. var bytes = new Uint8Array(buffer);
  5673. while (i < bytes.length) {
  5674. chr1 = bytes[i++];
  5675. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5676. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5677. enc1 = chr1 >> 2;
  5678. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5679. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5680. enc4 = chr3 & 63;
  5681. if (isNaN(chr2)) {
  5682. enc3 = enc4 = 64;
  5683. }
  5684. else if (isNaN(chr3)) {
  5685. enc4 = 64;
  5686. }
  5687. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5688. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5689. }
  5690. return "data:image/png;base64," + output;
  5691. };
  5692. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5693. if (bias === void 0) { bias = null; }
  5694. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5696. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5697. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5698. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5699. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5700. }
  5701. if (bias) {
  5702. minimum.x -= minimum.x * bias.x + bias.y;
  5703. minimum.y -= minimum.y * bias.x + bias.y;
  5704. minimum.z -= minimum.z * bias.x + bias.y;
  5705. maximum.x += maximum.x * bias.x + bias.y;
  5706. maximum.y += maximum.y * bias.x + bias.y;
  5707. maximum.z += maximum.z * bias.x + bias.y;
  5708. }
  5709. return {
  5710. minimum: minimum,
  5711. maximum: maximum
  5712. };
  5713. };
  5714. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5715. if (bias === void 0) { bias = null; }
  5716. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5717. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5718. if (!stride) {
  5719. stride = 3;
  5720. }
  5721. for (var index = start; index < start + count; index++) {
  5722. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5723. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5724. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5725. }
  5726. if (bias) {
  5727. minimum.x -= minimum.x * bias.x + bias.y;
  5728. minimum.y -= minimum.y * bias.x + bias.y;
  5729. minimum.z -= minimum.z * bias.x + bias.y;
  5730. maximum.x += maximum.x * bias.x + bias.y;
  5731. maximum.y += maximum.y * bias.x + bias.y;
  5732. maximum.z += maximum.z * bias.x + bias.y;
  5733. }
  5734. return {
  5735. minimum: minimum,
  5736. maximum: maximum
  5737. };
  5738. };
  5739. Tools.Vector2ArrayFeeder = function (array) {
  5740. return function (index) {
  5741. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5742. var length = isFloatArray ? array.length / 2 : array.length;
  5743. if (index >= length) {
  5744. return null;
  5745. }
  5746. if (isFloatArray) {
  5747. var fa = array;
  5748. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5749. }
  5750. var a = array;
  5751. return a[index];
  5752. };
  5753. };
  5754. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5755. if (bias === void 0) { bias = null; }
  5756. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5757. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5758. var i = 0;
  5759. var cur = feeder(i++);
  5760. while (cur) {
  5761. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5762. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5763. cur = feeder(i++);
  5764. }
  5765. if (bias) {
  5766. minimum.x -= minimum.x * bias.x + bias.y;
  5767. minimum.y -= minimum.y * bias.x + bias.y;
  5768. maximum.x += maximum.x * bias.x + bias.y;
  5769. maximum.y += maximum.y * bias.x + bias.y;
  5770. }
  5771. return {
  5772. minimum: minimum,
  5773. maximum: maximum
  5774. };
  5775. };
  5776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5778. return undefined;
  5779. return Array.isArray(obj) ? obj : [obj];
  5780. };
  5781. // Misc.
  5782. Tools.GetPointerPrefix = function () {
  5783. var eventPrefix = "pointer";
  5784. // Check if pointer events are supported
  5785. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5786. eventPrefix = "mouse";
  5787. }
  5788. return eventPrefix;
  5789. };
  5790. /**
  5791. * @param func - the function to be called
  5792. * @param requester - the object that will request the next frame. Falls back to window.
  5793. */
  5794. Tools.QueueNewFrame = function (func, requester) {
  5795. if (requester === void 0) { requester = window; }
  5796. if (requester.requestAnimationFrame) {
  5797. return requester.requestAnimationFrame(func);
  5798. }
  5799. else if (requester.msRequestAnimationFrame) {
  5800. return requester.msRequestAnimationFrame(func);
  5801. }
  5802. else if (requester.webkitRequestAnimationFrame) {
  5803. return requester.webkitRequestAnimationFrame(func);
  5804. }
  5805. else if (requester.mozRequestAnimationFrame) {
  5806. return requester.mozRequestAnimationFrame(func);
  5807. }
  5808. else if (requester.oRequestAnimationFrame) {
  5809. return requester.oRequestAnimationFrame(func);
  5810. }
  5811. else {
  5812. return window.setTimeout(func, 16);
  5813. }
  5814. };
  5815. Tools.RequestFullscreen = function (element) {
  5816. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5817. if (!requestFunction)
  5818. return;
  5819. requestFunction.call(element);
  5820. };
  5821. Tools.ExitFullscreen = function () {
  5822. if (document.exitFullscreen) {
  5823. document.exitFullscreen();
  5824. }
  5825. else if (document.mozCancelFullScreen) {
  5826. document.mozCancelFullScreen();
  5827. }
  5828. else if (document.webkitCancelFullScreen) {
  5829. document.webkitCancelFullScreen();
  5830. }
  5831. else if (document.msCancelFullScreen) {
  5832. document.msCancelFullScreen();
  5833. }
  5834. };
  5835. Tools.SetCorsBehavior = function (url, img) {
  5836. if (Tools.CorsBehavior) {
  5837. switch (typeof (Tools.CorsBehavior)) {
  5838. case "function":
  5839. var result = Tools.CorsBehavior(url);
  5840. if (result) {
  5841. img.crossOrigin = result;
  5842. }
  5843. break;
  5844. case "string":
  5845. default:
  5846. img.crossOrigin = Tools.CorsBehavior;
  5847. break;
  5848. }
  5849. }
  5850. };
  5851. // External files
  5852. Tools.CleanUrl = function (url) {
  5853. url = url.replace(/#/mg, "%23");
  5854. return url;
  5855. };
  5856. Tools.LoadImage = function (url, onload, onerror, database) {
  5857. if (url instanceof ArrayBuffer) {
  5858. url = Tools.EncodeArrayBufferTobase64(url);
  5859. }
  5860. url = Tools.CleanUrl(url);
  5861. url = Tools.PreprocessUrl(url);
  5862. var img = new Image();
  5863. if (url.substr(0, 5) !== "data:") {
  5864. Tools.SetCorsBehavior(url, img);
  5865. }
  5866. img.onload = function () {
  5867. onload(img);
  5868. };
  5869. img.onerror = function (err) {
  5870. Tools.Error("Error while trying to load image: " + url);
  5871. if (Tools.UseFallbackTexture) {
  5872. img.src = Tools.fallbackTexture;
  5873. onload(img);
  5874. }
  5875. else {
  5876. onerror();
  5877. }
  5878. };
  5879. var noIndexedDB = function () {
  5880. img.src = url;
  5881. };
  5882. var loadFromIndexedDB = function () {
  5883. database.loadImageFromDB(url, img);
  5884. };
  5885. //ANY database to do!
  5886. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5887. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5888. }
  5889. else {
  5890. if (url.indexOf("file:") !== 0) {
  5891. noIndexedDB();
  5892. }
  5893. else {
  5894. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5895. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5896. try {
  5897. var blobURL;
  5898. try {
  5899. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5900. }
  5901. catch (ex) {
  5902. // Chrome doesn't support oneTimeOnly parameter
  5903. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5904. }
  5905. img.src = blobURL;
  5906. }
  5907. catch (e) {
  5908. img.src = null;
  5909. }
  5910. }
  5911. else {
  5912. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5913. img.src = Tools.fallbackTexture;
  5914. }
  5915. }
  5916. }
  5917. return img;
  5918. };
  5919. //ANY
  5920. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5921. url = Tools.CleanUrl(url);
  5922. url = Tools.PreprocessUrl(url);
  5923. var noIndexedDB = function () {
  5924. var request = new XMLHttpRequest();
  5925. var loadUrl = Tools.BaseUrl + url;
  5926. request.open('GET', loadUrl, true);
  5927. if (useArrayBuffer) {
  5928. request.responseType = "arraybuffer";
  5929. }
  5930. request.onprogress = progressCallBack;
  5931. request.onreadystatechange = function () {
  5932. // In case of undefined state in some browsers.
  5933. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5934. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5935. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5936. callback(!useArrayBuffer ? request.responseText : request.response);
  5937. }
  5938. else {
  5939. if (onError) {
  5940. onError(request);
  5941. }
  5942. else {
  5943. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5944. }
  5945. }
  5946. }
  5947. };
  5948. request.send(null);
  5949. };
  5950. var loadFromIndexedDB = function () {
  5951. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5952. };
  5953. if (url.indexOf("file:") !== -1) {
  5954. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5955. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5956. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5957. }
  5958. else {
  5959. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5960. }
  5961. }
  5962. else {
  5963. // Caching all files
  5964. if (database && database.enableSceneOffline) {
  5965. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5966. }
  5967. else {
  5968. noIndexedDB();
  5969. }
  5970. }
  5971. };
  5972. /**
  5973. * Load a script (identified by an url). When the url returns, the
  5974. * content of this file is added into a new script element, attached to the DOM (body element)
  5975. */
  5976. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5977. var head = document.getElementsByTagName('head')[0];
  5978. var script = document.createElement('script');
  5979. script.type = 'text/javascript';
  5980. script.src = scriptUrl;
  5981. var self = this;
  5982. script.onload = function () {
  5983. if (onSuccess) {
  5984. onSuccess();
  5985. }
  5986. };
  5987. script.onerror = function () {
  5988. if (onError) {
  5989. onError();
  5990. }
  5991. };
  5992. head.appendChild(script);
  5993. };
  5994. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5995. var reader = new FileReader();
  5996. reader.onload = function (e) {
  5997. //target doesn't have result from ts 1.3
  5998. callback(e.target['result']);
  5999. };
  6000. reader.onprogress = progressCallback;
  6001. reader.readAsDataURL(fileToLoad);
  6002. };
  6003. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6004. var reader = new FileReader();
  6005. reader.onerror = function (e) {
  6006. Tools.Log("Error while reading file: " + fileToLoad.name);
  6007. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6008. };
  6009. reader.onload = function (e) {
  6010. //target doesn't have result from ts 1.3
  6011. callback(e.target['result']);
  6012. };
  6013. reader.onprogress = progressCallBack;
  6014. if (!useArrayBuffer) {
  6015. // Asynchronous read
  6016. reader.readAsText(fileToLoad);
  6017. }
  6018. else {
  6019. reader.readAsArrayBuffer(fileToLoad);
  6020. }
  6021. };
  6022. //returns a downloadable url to a file content.
  6023. Tools.FileAsURL = function (content) {
  6024. var fileBlob = new Blob([content]);
  6025. var url = window.URL || window.webkitURL;
  6026. var link = url.createObjectURL(fileBlob);
  6027. return link;
  6028. };
  6029. // Misc.
  6030. Tools.Format = function (value, decimals) {
  6031. if (decimals === void 0) { decimals = 2; }
  6032. return value.toFixed(decimals);
  6033. };
  6034. Tools.CheckExtends = function (v, min, max) {
  6035. if (v.x < min.x)
  6036. min.x = v.x;
  6037. if (v.y < min.y)
  6038. min.y = v.y;
  6039. if (v.z < min.z)
  6040. min.z = v.z;
  6041. if (v.x > max.x)
  6042. max.x = v.x;
  6043. if (v.y > max.y)
  6044. max.y = v.y;
  6045. if (v.z > max.z)
  6046. max.z = v.z;
  6047. };
  6048. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6049. for (var prop in source) {
  6050. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6051. continue;
  6052. }
  6053. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6054. continue;
  6055. }
  6056. var sourceValue = source[prop];
  6057. var typeOfSourceValue = typeof sourceValue;
  6058. if (typeOfSourceValue === "function") {
  6059. continue;
  6060. }
  6061. if (typeOfSourceValue === "object") {
  6062. if (sourceValue instanceof Array) {
  6063. destination[prop] = [];
  6064. if (sourceValue.length > 0) {
  6065. if (typeof sourceValue[0] == "object") {
  6066. for (var index = 0; index < sourceValue.length; index++) {
  6067. var clonedValue = cloneValue(sourceValue[index], destination);
  6068. if (destination[prop].indexOf(clonedValue) === -1) {
  6069. destination[prop].push(clonedValue);
  6070. }
  6071. }
  6072. }
  6073. else {
  6074. destination[prop] = sourceValue.slice(0);
  6075. }
  6076. }
  6077. }
  6078. else {
  6079. destination[prop] = cloneValue(sourceValue, destination);
  6080. }
  6081. }
  6082. else {
  6083. destination[prop] = sourceValue;
  6084. }
  6085. }
  6086. };
  6087. Tools.IsEmpty = function (obj) {
  6088. for (var i in obj) {
  6089. return false;
  6090. }
  6091. return true;
  6092. };
  6093. Tools.RegisterTopRootEvents = function (events) {
  6094. for (var index = 0; index < events.length; index++) {
  6095. var event = events[index];
  6096. window.addEventListener(event.name, event.handler, false);
  6097. try {
  6098. if (window.parent) {
  6099. window.parent.addEventListener(event.name, event.handler, false);
  6100. }
  6101. }
  6102. catch (e) {
  6103. // Silently fails...
  6104. }
  6105. }
  6106. };
  6107. Tools.UnregisterTopRootEvents = function (events) {
  6108. for (var index = 0; index < events.length; index++) {
  6109. var event = events[index];
  6110. window.removeEventListener(event.name, event.handler);
  6111. try {
  6112. if (window.parent) {
  6113. window.parent.removeEventListener(event.name, event.handler);
  6114. }
  6115. }
  6116. catch (e) {
  6117. // Silently fails...
  6118. }
  6119. }
  6120. };
  6121. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6122. if (mimeType === void 0) { mimeType = "image/png"; }
  6123. // Read the contents of the framebuffer
  6124. var numberOfChannelsByLine = width * 4;
  6125. var halfHeight = height / 2;
  6126. //Reading datas from WebGL
  6127. var data = engine.readPixels(0, 0, width, height);
  6128. //To flip image on Y axis.
  6129. for (var i = 0; i < halfHeight; i++) {
  6130. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6131. var currentCell = j + i * numberOfChannelsByLine;
  6132. var targetLine = height - i - 1;
  6133. var targetCell = j + targetLine * numberOfChannelsByLine;
  6134. var temp = data[currentCell];
  6135. data[currentCell] = data[targetCell];
  6136. data[targetCell] = temp;
  6137. }
  6138. }
  6139. // Create a 2D canvas to store the result
  6140. if (!screenshotCanvas) {
  6141. screenshotCanvas = document.createElement('canvas');
  6142. }
  6143. screenshotCanvas.width = width;
  6144. screenshotCanvas.height = height;
  6145. var context = screenshotCanvas.getContext('2d');
  6146. // Copy the pixels to a 2D canvas
  6147. var imageData = context.createImageData(width, height);
  6148. var castData = (imageData.data);
  6149. castData.set(data);
  6150. context.putImageData(imageData, 0, 0);
  6151. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6152. };
  6153. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6154. if (mimeType === void 0) { mimeType = "image/png"; }
  6155. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6156. if (successCallback) {
  6157. successCallback(base64Image);
  6158. }
  6159. else {
  6160. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6161. if (("download" in document.createElement("a"))) {
  6162. var a = window.document.createElement("a");
  6163. a.href = base64Image;
  6164. var date = new Date();
  6165. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6166. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6167. window.document.body.appendChild(a);
  6168. a.addEventListener("click", function () {
  6169. a.parentElement.removeChild(a);
  6170. });
  6171. a.click();
  6172. //Or opening a new tab with the image if it is not possible to automatically start download.
  6173. }
  6174. else {
  6175. var newWindow = window.open("");
  6176. var img = newWindow.document.createElement("img");
  6177. img.src = base64Image;
  6178. newWindow.document.body.appendChild(img);
  6179. }
  6180. }
  6181. };
  6182. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6183. if (mimeType === void 0) { mimeType = "image/png"; }
  6184. var width;
  6185. var height;
  6186. // If a precision value is specified
  6187. if (size.precision) {
  6188. width = Math.round(engine.getRenderWidth() * size.precision);
  6189. height = Math.round(width / engine.getAspectRatio(camera));
  6190. }
  6191. else if (size.width && size.height) {
  6192. width = size.width;
  6193. height = size.height;
  6194. }
  6195. else if (size.width && !size.height) {
  6196. width = size.width;
  6197. height = Math.round(width / engine.getAspectRatio(camera));
  6198. }
  6199. else if (size.height && !size.width) {
  6200. height = size.height;
  6201. width = Math.round(height * engine.getAspectRatio(camera));
  6202. }
  6203. else if (!isNaN(size)) {
  6204. height = size;
  6205. width = size;
  6206. }
  6207. else {
  6208. Tools.Error("Invalid 'size' parameter !");
  6209. return;
  6210. }
  6211. if (!screenshotCanvas) {
  6212. screenshotCanvas = document.createElement('canvas');
  6213. }
  6214. screenshotCanvas.width = width;
  6215. screenshotCanvas.height = height;
  6216. var renderContext = screenshotCanvas.getContext("2d");
  6217. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6218. var newWidth = width;
  6219. var newHeight = newWidth / ratio;
  6220. if (newHeight > height) {
  6221. newHeight = height;
  6222. newWidth = newHeight * ratio;
  6223. }
  6224. var offsetX = Math.max(0, width - newWidth) / 2;
  6225. var offsetY = Math.max(0, height - newHeight) / 2;
  6226. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6227. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6228. };
  6229. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6230. if (mimeType === void 0) { mimeType = "image/png"; }
  6231. if (samples === void 0) { samples = 1; }
  6232. var width;
  6233. var height;
  6234. //If a precision value is specified
  6235. if (size.precision) {
  6236. width = Math.round(engine.getRenderWidth() * size.precision);
  6237. height = Math.round(width / engine.getAspectRatio(camera));
  6238. size = { width: width, height: height };
  6239. }
  6240. else if (size.width && size.height) {
  6241. width = size.width;
  6242. height = size.height;
  6243. }
  6244. else if (size.width && !size.height) {
  6245. width = size.width;
  6246. height = Math.round(width / engine.getAspectRatio(camera));
  6247. size = { width: width, height: height };
  6248. }
  6249. else if (size.height && !size.width) {
  6250. height = size.height;
  6251. width = Math.round(height * engine.getAspectRatio(camera));
  6252. size = { width: width, height: height };
  6253. }
  6254. else if (!isNaN(size)) {
  6255. height = size;
  6256. width = size;
  6257. }
  6258. else {
  6259. Tools.Error("Invalid 'size' parameter !");
  6260. return;
  6261. }
  6262. var scene = camera.getScene();
  6263. var previousCamera = null;
  6264. if (scene.activeCamera !== camera) {
  6265. previousCamera = scene.activeCamera;
  6266. scene.activeCamera = camera;
  6267. }
  6268. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6269. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6270. texture.renderList = null;
  6271. texture.samples = samples;
  6272. texture.onAfterRenderObservable.add(function () {
  6273. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6274. });
  6275. scene.incrementRenderId();
  6276. scene.resetCachedMaterial();
  6277. texture.render(true);
  6278. texture.dispose();
  6279. if (previousCamera) {
  6280. scene.activeCamera = previousCamera;
  6281. }
  6282. camera.getProjectionMatrix(true); // Force cache refresh;
  6283. };
  6284. // XHR response validator for local file scenario
  6285. Tools.ValidateXHRData = function (xhr, dataType) {
  6286. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6287. if (dataType === void 0) { dataType = 7; }
  6288. try {
  6289. if (dataType & 1) {
  6290. if (xhr.responseText && xhr.responseText.length > 0) {
  6291. return true;
  6292. }
  6293. else if (dataType === 1) {
  6294. return false;
  6295. }
  6296. }
  6297. if (dataType & 2) {
  6298. // Check header width and height since there is no "TGA" magic number
  6299. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6300. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6301. return true;
  6302. }
  6303. else if (dataType === 2) {
  6304. return false;
  6305. }
  6306. }
  6307. if (dataType & 4) {
  6308. // Check for the "DDS" magic number
  6309. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6310. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6311. return true;
  6312. }
  6313. else {
  6314. return false;
  6315. }
  6316. }
  6317. }
  6318. catch (e) {
  6319. // Global protection
  6320. }
  6321. return false;
  6322. };
  6323. /**
  6324. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6325. * Be aware Math.random() could cause collisions, but:
  6326. * "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"
  6327. */
  6328. Tools.RandomId = function () {
  6329. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6330. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6331. return v.toString(16);
  6332. });
  6333. };
  6334. Object.defineProperty(Tools, "NoneLogLevel", {
  6335. get: function () {
  6336. return Tools._NoneLogLevel;
  6337. },
  6338. enumerable: true,
  6339. configurable: true
  6340. });
  6341. Object.defineProperty(Tools, "MessageLogLevel", {
  6342. get: function () {
  6343. return Tools._MessageLogLevel;
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(Tools, "WarningLogLevel", {
  6349. get: function () {
  6350. return Tools._WarningLogLevel;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Tools, "ErrorLogLevel", {
  6356. get: function () {
  6357. return Tools._ErrorLogLevel;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Object.defineProperty(Tools, "AllLogLevel", {
  6363. get: function () {
  6364. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Tools._AddLogEntry = function (entry) {
  6370. Tools._LogCache = entry + Tools._LogCache;
  6371. if (Tools.OnNewCacheEntry) {
  6372. Tools.OnNewCacheEntry(entry);
  6373. }
  6374. };
  6375. Tools._FormatMessage = function (message) {
  6376. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6377. var date = new Date();
  6378. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6379. };
  6380. Tools._LogDisabled = function (message) {
  6381. // nothing to do
  6382. };
  6383. Tools._LogEnabled = function (message) {
  6384. var formattedMessage = Tools._FormatMessage(message);
  6385. console.log("BJS - " + formattedMessage);
  6386. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6387. Tools._AddLogEntry(entry);
  6388. };
  6389. Tools._WarnDisabled = function (message) {
  6390. // nothing to do
  6391. };
  6392. Tools._WarnEnabled = function (message) {
  6393. var formattedMessage = Tools._FormatMessage(message);
  6394. console.warn("BJS - " + formattedMessage);
  6395. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6396. Tools._AddLogEntry(entry);
  6397. };
  6398. Tools._ErrorDisabled = function (message) {
  6399. // nothing to do
  6400. };
  6401. Tools._ErrorEnabled = function (message) {
  6402. Tools.errorsCount++;
  6403. var formattedMessage = Tools._FormatMessage(message);
  6404. console.error("BJS - " + formattedMessage);
  6405. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6406. Tools._AddLogEntry(entry);
  6407. };
  6408. Object.defineProperty(Tools, "LogCache", {
  6409. get: function () {
  6410. return Tools._LogCache;
  6411. },
  6412. enumerable: true,
  6413. configurable: true
  6414. });
  6415. Tools.ClearLogCache = function () {
  6416. Tools._LogCache = "";
  6417. Tools.errorsCount = 0;
  6418. };
  6419. Object.defineProperty(Tools, "LogLevels", {
  6420. set: function (level) {
  6421. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6422. Tools.Log = Tools._LogEnabled;
  6423. }
  6424. else {
  6425. Tools.Log = Tools._LogDisabled;
  6426. }
  6427. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6428. Tools.Warn = Tools._WarnEnabled;
  6429. }
  6430. else {
  6431. Tools.Warn = Tools._WarnDisabled;
  6432. }
  6433. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6434. Tools.Error = Tools._ErrorEnabled;
  6435. }
  6436. else {
  6437. Tools.Error = Tools._ErrorDisabled;
  6438. }
  6439. },
  6440. enumerable: true,
  6441. configurable: true
  6442. });
  6443. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6444. get: function () {
  6445. return Tools._PerformanceNoneLogLevel;
  6446. },
  6447. enumerable: true,
  6448. configurable: true
  6449. });
  6450. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6451. get: function () {
  6452. return Tools._PerformanceUserMarkLogLevel;
  6453. },
  6454. enumerable: true,
  6455. configurable: true
  6456. });
  6457. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6458. get: function () {
  6459. return Tools._PerformanceConsoleLogLevel;
  6460. },
  6461. enumerable: true,
  6462. configurable: true
  6463. });
  6464. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6465. set: function (level) {
  6466. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6467. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6468. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6469. return;
  6470. }
  6471. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6472. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6473. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6474. return;
  6475. }
  6476. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6477. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6478. },
  6479. enumerable: true,
  6480. configurable: true
  6481. });
  6482. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6483. };
  6484. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6485. };
  6486. Tools._StartUserMark = function (counterName, condition) {
  6487. if (condition === void 0) { condition = true; }
  6488. if (!condition || !Tools._performance.mark) {
  6489. return;
  6490. }
  6491. Tools._performance.mark(counterName + "-Begin");
  6492. };
  6493. Tools._EndUserMark = function (counterName, condition) {
  6494. if (condition === void 0) { condition = true; }
  6495. if (!condition || !Tools._performance.mark) {
  6496. return;
  6497. }
  6498. Tools._performance.mark(counterName + "-End");
  6499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6500. };
  6501. Tools._StartPerformanceConsole = function (counterName, condition) {
  6502. if (condition === void 0) { condition = true; }
  6503. if (!condition) {
  6504. return;
  6505. }
  6506. Tools._StartUserMark(counterName, condition);
  6507. if (console.time) {
  6508. console.time(counterName);
  6509. }
  6510. };
  6511. Tools._EndPerformanceConsole = function (counterName, condition) {
  6512. if (condition === void 0) { condition = true; }
  6513. if (!condition) {
  6514. return;
  6515. }
  6516. Tools._EndUserMark(counterName, condition);
  6517. if (console.time) {
  6518. console.timeEnd(counterName);
  6519. }
  6520. };
  6521. Object.defineProperty(Tools, "Now", {
  6522. get: function () {
  6523. if (window.performance && window.performance.now) {
  6524. return window.performance.now();
  6525. }
  6526. return new Date().getTime();
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. /**
  6532. * This method will return the name of the class used to create the instance of the given object.
  6533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6534. * @param object the object to get the class name from
  6535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6536. */
  6537. Tools.GetClassName = function (object, isType) {
  6538. if (isType === void 0) { isType = false; }
  6539. var name = null;
  6540. if (!isType && object.getClassName) {
  6541. name = object.getClassName();
  6542. }
  6543. else {
  6544. if (object instanceof Object) {
  6545. var classObj = isType ? object : Object.getPrototypeOf(object);
  6546. name = classObj.constructor["__bjsclassName__"];
  6547. }
  6548. if (!name) {
  6549. name = typeof object;
  6550. }
  6551. }
  6552. return name;
  6553. };
  6554. Tools.first = function (array, predicate) {
  6555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6556. var el = array_1[_i];
  6557. if (predicate(el)) {
  6558. return el;
  6559. }
  6560. }
  6561. };
  6562. /**
  6563. * This method will return the name of the full name of the class, including its owning module (if any).
  6564. * 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).
  6565. * @param object the object to get the class name from
  6566. * @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.
  6567. */
  6568. Tools.getFullClassName = function (object, isType) {
  6569. if (isType === void 0) { isType = false; }
  6570. var className = null;
  6571. var moduleName = null;
  6572. if (!isType && object.getClassName) {
  6573. className = object.getClassName();
  6574. }
  6575. else {
  6576. if (object instanceof Object) {
  6577. var classObj = isType ? object : Object.getPrototypeOf(object);
  6578. className = classObj.constructor["__bjsclassName__"];
  6579. moduleName = classObj.constructor["__bjsmoduleName__"];
  6580. }
  6581. if (!className) {
  6582. className = typeof object;
  6583. }
  6584. }
  6585. if (!className) {
  6586. return null;
  6587. }
  6588. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6589. };
  6590. /**
  6591. * 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.
  6592. * @param array
  6593. */
  6594. Tools.arrayOrStringFeeder = function (array) {
  6595. return function (index) {
  6596. if (index >= array.length) {
  6597. return null;
  6598. }
  6599. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6600. if (val && val.getHashCode) {
  6601. val = val.getHashCode();
  6602. }
  6603. if (typeof val === "string") {
  6604. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6605. }
  6606. return val;
  6607. };
  6608. };
  6609. /**
  6610. * Compute the hashCode of a stream of number
  6611. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6612. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6613. * @return the hash code computed
  6614. */
  6615. Tools.hashCodeFromStream = function (feeder) {
  6616. // Based from here: http://stackoverflow.com/a/7616484/802124
  6617. var hash = 0;
  6618. var index = 0;
  6619. var chr = feeder(index++);
  6620. while (chr != null) {
  6621. hash = ((hash << 5) - hash) + chr;
  6622. hash |= 0; // Convert to 32bit integer
  6623. chr = feeder(index++);
  6624. }
  6625. return hash;
  6626. };
  6627. Tools.BaseUrl = "";
  6628. Tools.CorsBehavior = "anonymous";
  6629. Tools.UseFallbackTexture = true;
  6630. // Used in case of a texture loading problem
  6631. 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";
  6632. Tools.PreprocessUrl = function (url) {
  6633. return url;
  6634. };
  6635. // Logs
  6636. Tools._NoneLogLevel = 0;
  6637. Tools._MessageLogLevel = 1;
  6638. Tools._WarningLogLevel = 2;
  6639. Tools._ErrorLogLevel = 4;
  6640. Tools._LogCache = "";
  6641. Tools.errorsCount = 0;
  6642. Tools.Log = Tools._LogEnabled;
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. Tools.Error = Tools._ErrorEnabled;
  6645. // Performances
  6646. Tools._PerformanceNoneLogLevel = 0;
  6647. Tools._PerformanceUserMarkLogLevel = 1;
  6648. Tools._PerformanceConsoleLogLevel = 2;
  6649. Tools._performance = window.performance;
  6650. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6651. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6652. return Tools;
  6653. }());
  6654. BABYLON.Tools = Tools;
  6655. /**
  6656. * This class is used to track a performance counter which is number based.
  6657. * The user has access to many properties which give statistics of different nature
  6658. *
  6659. * The implementer can track two kinds of Performance Counter: time and count
  6660. * 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.
  6661. * 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.
  6662. */
  6663. var PerfCounter = (function () {
  6664. function PerfCounter() {
  6665. this._startMonitoringTime = 0;
  6666. this._min = 0;
  6667. this._max = 0;
  6668. this._average = 0;
  6669. this._lastSecAverage = 0;
  6670. this._current = 0;
  6671. this._totalValueCount = 0;
  6672. this._totalAccumulated = 0;
  6673. this._lastSecAccumulated = 0;
  6674. this._lastSecTime = 0;
  6675. this._lastSecValueCount = 0;
  6676. }
  6677. Object.defineProperty(PerfCounter.prototype, "min", {
  6678. /**
  6679. * Returns the smallest value ever
  6680. */
  6681. get: function () {
  6682. return this._min;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Object.defineProperty(PerfCounter.prototype, "max", {
  6688. /**
  6689. * Returns the biggest value ever
  6690. */
  6691. get: function () {
  6692. return this._max;
  6693. },
  6694. enumerable: true,
  6695. configurable: true
  6696. });
  6697. Object.defineProperty(PerfCounter.prototype, "average", {
  6698. /**
  6699. * Returns the average value since the performance counter is running
  6700. */
  6701. get: function () {
  6702. return this._average;
  6703. },
  6704. enumerable: true,
  6705. configurable: true
  6706. });
  6707. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6708. /**
  6709. * Returns the average value of the last second the counter was monitored
  6710. */
  6711. get: function () {
  6712. return this._lastSecAverage;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(PerfCounter.prototype, "current", {
  6718. /**
  6719. * Returns the current value
  6720. */
  6721. get: function () {
  6722. return this._current;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(PerfCounter.prototype, "total", {
  6728. get: function () {
  6729. return this._totalAccumulated;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. /**
  6735. * Call this method to start monitoring a new frame.
  6736. * 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.
  6737. */
  6738. PerfCounter.prototype.fetchNewFrame = function () {
  6739. this._totalValueCount++;
  6740. this._current = 0;
  6741. this._lastSecValueCount++;
  6742. };
  6743. /**
  6744. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6745. * @param newCount the count value to add to the monitored count
  6746. * @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.
  6747. */
  6748. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6749. if (!PerfCounter.Enabled) {
  6750. return;
  6751. }
  6752. this._current += newCount;
  6753. if (fetchResult) {
  6754. this._fetchResult();
  6755. }
  6756. };
  6757. /**
  6758. * Start monitoring this performance counter
  6759. */
  6760. PerfCounter.prototype.beginMonitoring = function () {
  6761. if (!PerfCounter.Enabled) {
  6762. return;
  6763. }
  6764. this._startMonitoringTime = Tools.Now;
  6765. };
  6766. /**
  6767. * Compute the time lapsed since the previous beginMonitoring() call.
  6768. * @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
  6769. */
  6770. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6771. if (newFrame === void 0) { newFrame = true; }
  6772. if (!PerfCounter.Enabled) {
  6773. return;
  6774. }
  6775. if (newFrame) {
  6776. this.fetchNewFrame();
  6777. }
  6778. var currentTime = Tools.Now;
  6779. this._current = currentTime - this._startMonitoringTime;
  6780. if (newFrame) {
  6781. this._fetchResult();
  6782. }
  6783. };
  6784. PerfCounter.prototype._fetchResult = function () {
  6785. this._totalAccumulated += this._current;
  6786. this._lastSecAccumulated += this._current;
  6787. // Min/Max update
  6788. this._min = Math.min(this._min, this._current);
  6789. this._max = Math.max(this._max, this._current);
  6790. this._average = this._totalAccumulated / this._totalValueCount;
  6791. // Reset last sec?
  6792. var now = Tools.Now;
  6793. if ((now - this._lastSecTime) > 1000) {
  6794. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6795. this._lastSecTime = now;
  6796. this._lastSecAccumulated = 0;
  6797. this._lastSecValueCount = 0;
  6798. }
  6799. };
  6800. PerfCounter.Enabled = true;
  6801. return PerfCounter;
  6802. }());
  6803. BABYLON.PerfCounter = PerfCounter;
  6804. /**
  6805. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6806. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6807. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6808. * @param name The name of the class, case should be preserved
  6809. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6810. */
  6811. function className(name, module) {
  6812. return function (target) {
  6813. target["__bjsclassName__"] = name;
  6814. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6815. };
  6816. }
  6817. BABYLON.className = className;
  6818. /**
  6819. * An implementation of a loop for asynchronous functions.
  6820. */
  6821. var AsyncLoop = (function () {
  6822. /**
  6823. * Constroctor.
  6824. * @param iterations the number of iterations.
  6825. * @param _fn the function to run each iteration
  6826. * @param _successCallback the callback that will be called upon succesful execution
  6827. * @param offset starting offset.
  6828. */
  6829. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6830. if (offset === void 0) { offset = 0; }
  6831. this.iterations = iterations;
  6832. this._fn = _fn;
  6833. this._successCallback = _successCallback;
  6834. this.index = offset - 1;
  6835. this._done = false;
  6836. }
  6837. /**
  6838. * Execute the next iteration. Must be called after the last iteration was finished.
  6839. */
  6840. AsyncLoop.prototype.executeNext = function () {
  6841. if (!this._done) {
  6842. if (this.index + 1 < this.iterations) {
  6843. ++this.index;
  6844. this._fn(this);
  6845. }
  6846. else {
  6847. this.breakLoop();
  6848. }
  6849. }
  6850. };
  6851. /**
  6852. * Break the loop and run the success callback.
  6853. */
  6854. AsyncLoop.prototype.breakLoop = function () {
  6855. this._done = true;
  6856. this._successCallback();
  6857. };
  6858. /**
  6859. * Helper function
  6860. */
  6861. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6862. if (offset === void 0) { offset = 0; }
  6863. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6864. loop.executeNext();
  6865. return loop;
  6866. };
  6867. /**
  6868. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6869. * @param iterations total number of iterations
  6870. * @param syncedIterations number of synchronous iterations in each async iteration.
  6871. * @param fn the function to call each iteration.
  6872. * @param callback a success call back that will be called when iterating stops.
  6873. * @param breakFunction a break condition (optional)
  6874. * @param timeout timeout settings for the setTimeout function. default - 0.
  6875. * @constructor
  6876. */
  6877. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6878. if (timeout === void 0) { timeout = 0; }
  6879. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6880. if (breakFunction && breakFunction())
  6881. loop.breakLoop();
  6882. else {
  6883. setTimeout(function () {
  6884. for (var i = 0; i < syncedIterations; ++i) {
  6885. var iteration = (loop.index * syncedIterations) + i;
  6886. if (iteration >= iterations)
  6887. break;
  6888. fn(iteration);
  6889. if (breakFunction && breakFunction()) {
  6890. loop.breakLoop();
  6891. break;
  6892. }
  6893. }
  6894. loop.executeNext();
  6895. }, timeout);
  6896. }
  6897. }, callback);
  6898. };
  6899. return AsyncLoop;
  6900. }());
  6901. BABYLON.AsyncLoop = AsyncLoop;
  6902. })(BABYLON || (BABYLON = {}));
  6903. //# sourceMappingURL=babylon.tools.js.map
  6904. var BABYLON;
  6905. (function (BABYLON) {
  6906. var Internals;
  6907. (function (Internals) {
  6908. var _AlphaState = (function () {
  6909. /**
  6910. * Initializes the state.
  6911. */
  6912. function _AlphaState() {
  6913. this._isAlphaBlendDirty = false;
  6914. this._isBlendFunctionParametersDirty = false;
  6915. this._isBlendEquationParametersDirty = false;
  6916. this._isBlendConstantsDirty = false;
  6917. this._alphaBlend = false;
  6918. this._blendFunctionParameters = new Array(4);
  6919. this._blendEquationParameters = new Array(2);
  6920. this._blendConstants = new Array(4);
  6921. this.reset();
  6922. }
  6923. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6924. get: function () {
  6925. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6931. get: function () {
  6932. return this._alphaBlend;
  6933. },
  6934. set: function (value) {
  6935. if (this._alphaBlend === value) {
  6936. return;
  6937. }
  6938. this._alphaBlend = value;
  6939. this._isAlphaBlendDirty = true;
  6940. },
  6941. enumerable: true,
  6942. configurable: true
  6943. });
  6944. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6945. if (this._blendConstants[0] === r &&
  6946. this._blendConstants[1] === g &&
  6947. this._blendConstants[2] === b &&
  6948. this._blendConstants[3] === a) {
  6949. return;
  6950. }
  6951. this._blendConstants[0] = r;
  6952. this._blendConstants[1] = g;
  6953. this._blendConstants[2] = b;
  6954. this._blendConstants[3] = a;
  6955. this._isBlendConstantsDirty = true;
  6956. };
  6957. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6958. if (this._blendFunctionParameters[0] === value0 &&
  6959. this._blendFunctionParameters[1] === value1 &&
  6960. this._blendFunctionParameters[2] === value2 &&
  6961. this._blendFunctionParameters[3] === value3) {
  6962. return;
  6963. }
  6964. this._blendFunctionParameters[0] = value0;
  6965. this._blendFunctionParameters[1] = value1;
  6966. this._blendFunctionParameters[2] = value2;
  6967. this._blendFunctionParameters[3] = value3;
  6968. this._isBlendFunctionParametersDirty = true;
  6969. };
  6970. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6971. if (this._blendEquationParameters[0] === rgb &&
  6972. this._blendEquationParameters[1] === alpha) {
  6973. return;
  6974. }
  6975. this._blendEquationParameters[0] = rgb;
  6976. this._blendEquationParameters[1] = alpha;
  6977. this._isBlendEquationParametersDirty = true;
  6978. };
  6979. _AlphaState.prototype.reset = function () {
  6980. this._alphaBlend = false;
  6981. this._blendFunctionParameters[0] = null;
  6982. this._blendFunctionParameters[1] = null;
  6983. this._blendFunctionParameters[2] = null;
  6984. this._blendFunctionParameters[3] = null;
  6985. this._blendEquationParameters[0] = null;
  6986. this._blendEquationParameters[1] = null;
  6987. this._blendConstants[0] = null;
  6988. this._blendConstants[1] = null;
  6989. this._blendConstants[2] = null;
  6990. this._blendConstants[3] = null;
  6991. this._isAlphaBlendDirty = true;
  6992. this._isBlendFunctionParametersDirty = false;
  6993. this._isBlendEquationParametersDirty = false;
  6994. this._isBlendConstantsDirty = false;
  6995. };
  6996. _AlphaState.prototype.apply = function (gl) {
  6997. if (!this.isDirty) {
  6998. return;
  6999. }
  7000. // Alpha blend
  7001. if (this._isAlphaBlendDirty) {
  7002. if (this._alphaBlend) {
  7003. gl.enable(gl.BLEND);
  7004. }
  7005. else {
  7006. gl.disable(gl.BLEND);
  7007. }
  7008. this._isAlphaBlendDirty = false;
  7009. }
  7010. // Alpha function
  7011. if (this._isBlendFunctionParametersDirty) {
  7012. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7013. this._isBlendFunctionParametersDirty = false;
  7014. }
  7015. // Alpha equation
  7016. if (this._isBlendEquationParametersDirty) {
  7017. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7018. this._isBlendEquationParametersDirty = false;
  7019. }
  7020. // Constants
  7021. if (this._isBlendConstantsDirty) {
  7022. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7023. this._isBlendConstantsDirty = false;
  7024. }
  7025. };
  7026. return _AlphaState;
  7027. }());
  7028. Internals._AlphaState = _AlphaState;
  7029. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7030. })(BABYLON || (BABYLON = {}));
  7031. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7032. var BABYLON;
  7033. (function (BABYLON) {
  7034. var Internals;
  7035. (function (Internals) {
  7036. var _DepthCullingState = (function () {
  7037. /**
  7038. * Initializes the state.
  7039. */
  7040. function _DepthCullingState() {
  7041. this._isDepthTestDirty = false;
  7042. this._isDepthMaskDirty = false;
  7043. this._isDepthFuncDirty = false;
  7044. this._isCullFaceDirty = false;
  7045. this._isCullDirty = false;
  7046. this._isZOffsetDirty = false;
  7047. this.reset();
  7048. }
  7049. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7050. get: function () {
  7051. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7052. },
  7053. enumerable: true,
  7054. configurable: true
  7055. });
  7056. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7057. get: function () {
  7058. return this._zOffset;
  7059. },
  7060. set: function (value) {
  7061. if (this._zOffset === value) {
  7062. return;
  7063. }
  7064. this._zOffset = value;
  7065. this._isZOffsetDirty = true;
  7066. },
  7067. enumerable: true,
  7068. configurable: true
  7069. });
  7070. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7071. get: function () {
  7072. return this._cullFace;
  7073. },
  7074. set: function (value) {
  7075. if (this._cullFace === value) {
  7076. return;
  7077. }
  7078. this._cullFace = value;
  7079. this._isCullFaceDirty = true;
  7080. },
  7081. enumerable: true,
  7082. configurable: true
  7083. });
  7084. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7085. get: function () {
  7086. return this._cull;
  7087. },
  7088. set: function (value) {
  7089. if (this._cull === value) {
  7090. return;
  7091. }
  7092. this._cull = value;
  7093. this._isCullDirty = true;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7099. get: function () {
  7100. return this._depthFunc;
  7101. },
  7102. set: function (value) {
  7103. if (this._depthFunc === value) {
  7104. return;
  7105. }
  7106. this._depthFunc = value;
  7107. this._isDepthFuncDirty = true;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7113. get: function () {
  7114. return this._depthMask;
  7115. },
  7116. set: function (value) {
  7117. if (this._depthMask === value) {
  7118. return;
  7119. }
  7120. this._depthMask = value;
  7121. this._isDepthMaskDirty = true;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7127. get: function () {
  7128. return this._depthTest;
  7129. },
  7130. set: function (value) {
  7131. if (this._depthTest === value) {
  7132. return;
  7133. }
  7134. this._depthTest = value;
  7135. this._isDepthTestDirty = true;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. _DepthCullingState.prototype.reset = function () {
  7141. this._depthMask = true;
  7142. this._depthTest = true;
  7143. this._depthFunc = null;
  7144. this._cullFace = null;
  7145. this._cull = null;
  7146. this._zOffset = 0;
  7147. this._isDepthTestDirty = true;
  7148. this._isDepthMaskDirty = true;
  7149. this._isDepthFuncDirty = false;
  7150. this._isCullFaceDirty = false;
  7151. this._isCullDirty = false;
  7152. this._isZOffsetDirty = false;
  7153. };
  7154. _DepthCullingState.prototype.apply = function (gl) {
  7155. if (!this.isDirty) {
  7156. return;
  7157. }
  7158. // Cull
  7159. if (this._isCullDirty) {
  7160. if (this.cull) {
  7161. gl.enable(gl.CULL_FACE);
  7162. }
  7163. else {
  7164. gl.disable(gl.CULL_FACE);
  7165. }
  7166. this._isCullDirty = false;
  7167. }
  7168. // Cull face
  7169. if (this._isCullFaceDirty) {
  7170. gl.cullFace(this.cullFace);
  7171. this._isCullFaceDirty = false;
  7172. }
  7173. // Depth mask
  7174. if (this._isDepthMaskDirty) {
  7175. gl.depthMask(this.depthMask);
  7176. this._isDepthMaskDirty = false;
  7177. }
  7178. // Depth test
  7179. if (this._isDepthTestDirty) {
  7180. if (this.depthTest) {
  7181. gl.enable(gl.DEPTH_TEST);
  7182. }
  7183. else {
  7184. gl.disable(gl.DEPTH_TEST);
  7185. }
  7186. this._isDepthTestDirty = false;
  7187. }
  7188. // Depth func
  7189. if (this._isDepthFuncDirty) {
  7190. gl.depthFunc(this.depthFunc);
  7191. this._isDepthFuncDirty = false;
  7192. }
  7193. // zOffset
  7194. if (this._isZOffsetDirty) {
  7195. if (this.zOffset) {
  7196. gl.enable(gl.POLYGON_OFFSET_FILL);
  7197. gl.polygonOffset(this.zOffset, 0);
  7198. }
  7199. else {
  7200. gl.disable(gl.POLYGON_OFFSET_FILL);
  7201. }
  7202. this._isZOffsetDirty = false;
  7203. }
  7204. };
  7205. return _DepthCullingState;
  7206. }());
  7207. Internals._DepthCullingState = _DepthCullingState;
  7208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7209. })(BABYLON || (BABYLON = {}));
  7210. //# sourceMappingURL=babylon.depthCullingState.js.map
  7211. var BABYLON;
  7212. (function (BABYLON) {
  7213. var Internals;
  7214. (function (Internals) {
  7215. var _StencilState = (function () {
  7216. function _StencilState() {
  7217. this._isStencilTestDirty = false;
  7218. this._isStencilMaskDirty = false;
  7219. this._isStencilFuncDirty = false;
  7220. this._isStencilOpDirty = false;
  7221. this.reset();
  7222. }
  7223. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7224. get: function () {
  7225. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7226. },
  7227. enumerable: true,
  7228. configurable: true
  7229. });
  7230. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7231. get: function () {
  7232. return this._stencilFunc;
  7233. },
  7234. set: function (value) {
  7235. if (this._stencilFunc === value) {
  7236. return;
  7237. }
  7238. this._stencilFunc = value;
  7239. this._isStencilFuncDirty = true;
  7240. },
  7241. enumerable: true,
  7242. configurable: true
  7243. });
  7244. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7245. get: function () {
  7246. return this._stencilFuncRef;
  7247. },
  7248. set: function (value) {
  7249. if (this._stencilFuncRef === value) {
  7250. return;
  7251. }
  7252. this._stencilFuncRef = value;
  7253. this._isStencilFuncDirty = true;
  7254. },
  7255. enumerable: true,
  7256. configurable: true
  7257. });
  7258. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7259. get: function () {
  7260. return this._stencilFuncMask;
  7261. },
  7262. set: function (value) {
  7263. if (this._stencilFuncMask === value) {
  7264. return;
  7265. }
  7266. this._stencilFuncMask = value;
  7267. this._isStencilFuncDirty = true;
  7268. },
  7269. enumerable: true,
  7270. configurable: true
  7271. });
  7272. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7273. get: function () {
  7274. return this._stencilOpStencilFail;
  7275. },
  7276. set: function (value) {
  7277. if (this._stencilOpStencilFail === value) {
  7278. return;
  7279. }
  7280. this._stencilOpStencilFail = value;
  7281. this._isStencilOpDirty = true;
  7282. },
  7283. enumerable: true,
  7284. configurable: true
  7285. });
  7286. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7287. get: function () {
  7288. return this._stencilOpDepthFail;
  7289. },
  7290. set: function (value) {
  7291. if (this._stencilOpDepthFail === value) {
  7292. return;
  7293. }
  7294. this._stencilOpDepthFail = value;
  7295. this._isStencilOpDirty = true;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7301. get: function () {
  7302. return this._stencilOpStencilDepthPass;
  7303. },
  7304. set: function (value) {
  7305. if (this._stencilOpStencilDepthPass === value) {
  7306. return;
  7307. }
  7308. this._stencilOpStencilDepthPass = value;
  7309. this._isStencilOpDirty = true;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7315. get: function () {
  7316. return this._stencilMask;
  7317. },
  7318. set: function (value) {
  7319. if (this._stencilMask === value) {
  7320. return;
  7321. }
  7322. this._stencilMask = value;
  7323. this._isStencilMaskDirty = true;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7329. get: function () {
  7330. return this._stencilTest;
  7331. },
  7332. set: function (value) {
  7333. if (this._stencilTest === value) {
  7334. return;
  7335. }
  7336. this._stencilTest = value;
  7337. this._isStencilTestDirty = true;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. _StencilState.prototype.reset = function () {
  7343. this._stencilTest = false;
  7344. this._stencilMask = 0xFF;
  7345. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7346. this._stencilFuncRef = 1;
  7347. this._stencilFuncMask = 0xFF;
  7348. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7349. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7350. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7351. this._isStencilTestDirty = true;
  7352. this._isStencilMaskDirty = true;
  7353. this._isStencilFuncDirty = true;
  7354. this._isStencilOpDirty = true;
  7355. };
  7356. _StencilState.prototype.apply = function (gl) {
  7357. if (!this.isDirty) {
  7358. return;
  7359. }
  7360. // Stencil test
  7361. if (this._isStencilTestDirty) {
  7362. if (this.stencilTest) {
  7363. gl.enable(gl.STENCIL_TEST);
  7364. }
  7365. else {
  7366. gl.disable(gl.STENCIL_TEST);
  7367. }
  7368. this._isStencilTestDirty = false;
  7369. }
  7370. // Stencil mask
  7371. if (this._isStencilMaskDirty) {
  7372. gl.stencilMask(this.stencilMask);
  7373. this._isStencilMaskDirty = false;
  7374. }
  7375. // Stencil func
  7376. if (this._isStencilFuncDirty) {
  7377. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7378. this._isStencilFuncDirty = false;
  7379. }
  7380. // Stencil op
  7381. if (this._isStencilOpDirty) {
  7382. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7383. this._isStencilOpDirty = false;
  7384. }
  7385. };
  7386. return _StencilState;
  7387. }());
  7388. Internals._StencilState = _StencilState;
  7389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7390. })(BABYLON || (BABYLON = {}));
  7391. //# sourceMappingURL=babylon.stencilState.js.map
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7395. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7396. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7397. gl.compileShader(shader);
  7398. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7399. throw new Error(gl.getShaderInfoLog(shader));
  7400. }
  7401. return shader;
  7402. };
  7403. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7404. var magFilter = gl.NEAREST;
  7405. var minFilter = gl.NEAREST;
  7406. switch (samplingMode) {
  7407. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7408. magFilter = gl.LINEAR;
  7409. if (generateMipMaps) {
  7410. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7411. }
  7412. else {
  7413. minFilter = gl.LINEAR;
  7414. }
  7415. break;
  7416. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7417. magFilter = gl.LINEAR;
  7418. if (generateMipMaps) {
  7419. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7420. }
  7421. else {
  7422. minFilter = gl.LINEAR;
  7423. }
  7424. break;
  7425. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7426. magFilter = gl.NEAREST;
  7427. if (generateMipMaps) {
  7428. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7429. }
  7430. else {
  7431. minFilter = gl.NEAREST;
  7432. }
  7433. break;
  7434. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7435. magFilter = gl.NEAREST;
  7436. if (generateMipMaps) {
  7437. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7438. }
  7439. else {
  7440. minFilter = gl.NEAREST;
  7441. }
  7442. break;
  7443. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7444. magFilter = gl.NEAREST;
  7445. if (generateMipMaps) {
  7446. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7447. }
  7448. else {
  7449. minFilter = gl.LINEAR;
  7450. }
  7451. break;
  7452. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7453. magFilter = gl.NEAREST;
  7454. if (generateMipMaps) {
  7455. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7456. }
  7457. else {
  7458. minFilter = gl.LINEAR;
  7459. }
  7460. break;
  7461. case BABYLON.Texture.NEAREST_LINEAR:
  7462. magFilter = gl.NEAREST;
  7463. minFilter = gl.LINEAR;
  7464. break;
  7465. case BABYLON.Texture.NEAREST_NEAREST:
  7466. magFilter = gl.NEAREST;
  7467. minFilter = gl.NEAREST;
  7468. break;
  7469. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7470. magFilter = gl.LINEAR;
  7471. if (generateMipMaps) {
  7472. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7473. }
  7474. else {
  7475. minFilter = gl.NEAREST;
  7476. }
  7477. break;
  7478. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7479. magFilter = gl.LINEAR;
  7480. if (generateMipMaps) {
  7481. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7482. }
  7483. else {
  7484. minFilter = gl.NEAREST;
  7485. }
  7486. break;
  7487. case BABYLON.Texture.LINEAR_LINEAR:
  7488. magFilter = gl.LINEAR;
  7489. minFilter = gl.LINEAR;
  7490. break;
  7491. case BABYLON.Texture.LINEAR_NEAREST:
  7492. magFilter = gl.LINEAR;
  7493. minFilter = gl.NEAREST;
  7494. break;
  7495. }
  7496. return {
  7497. min: minFilter,
  7498. mag: magFilter
  7499. };
  7500. };
  7501. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7502. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7503. var img;
  7504. var onload = function () {
  7505. loadedImages[index] = img;
  7506. loadedImages._internalCount++;
  7507. if (scene) {
  7508. scene._removePendingData(img);
  7509. }
  7510. if (loadedImages._internalCount === 6) {
  7511. onfinish(loadedImages);
  7512. }
  7513. };
  7514. var onerror = function () {
  7515. if (scene) {
  7516. scene._removePendingData(img);
  7517. }
  7518. if (onErrorCallBack) {
  7519. onErrorCallBack();
  7520. }
  7521. };
  7522. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7523. if (scene) {
  7524. scene._addPendingData(img);
  7525. }
  7526. };
  7527. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7528. if (onError === void 0) { onError = null; }
  7529. var loadedImages = [];
  7530. loadedImages._internalCount = 0;
  7531. for (var index = 0; index < 6; index++) {
  7532. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7533. }
  7534. };
  7535. var BufferPointer = (function () {
  7536. function BufferPointer() {
  7537. }
  7538. return BufferPointer;
  7539. }());
  7540. var InstancingAttributeInfo = (function () {
  7541. function InstancingAttributeInfo() {
  7542. }
  7543. return InstancingAttributeInfo;
  7544. }());
  7545. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7546. /**
  7547. * Define options used to create a render target texture
  7548. */
  7549. var RenderTargetCreationOptions = (function () {
  7550. function RenderTargetCreationOptions() {
  7551. }
  7552. return RenderTargetCreationOptions;
  7553. }());
  7554. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7555. /**
  7556. * Regroup several parameters relative to the browser in use
  7557. */
  7558. var EngineCapabilities = (function () {
  7559. function EngineCapabilities() {
  7560. }
  7561. return EngineCapabilities;
  7562. }());
  7563. BABYLON.EngineCapabilities = EngineCapabilities;
  7564. /**
  7565. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7566. */
  7567. var Engine = (function () {
  7568. /**
  7569. * @constructor
  7570. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7571. * @param {boolean} [antialias] - enable antialias
  7572. * @param options - further options to be sent to the getContext function
  7573. */
  7574. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7575. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7576. var _this = this;
  7577. // Public members
  7578. this.forcePOTTextures = false;
  7579. this.isFullscreen = false;
  7580. this.isPointerLock = false;
  7581. this.cullBackFaces = true;
  7582. this.renderEvenInBackground = true;
  7583. this.preventCacheWipeBetweenFrames = false;
  7584. // To enable/disable IDB support and avoid XHR on .manifest
  7585. this.enableOfflineSupport = false;
  7586. this.scenes = new Array();
  7587. this.postProcesses = new Array();
  7588. // Observables
  7589. /**
  7590. * Observable event triggered each time the rendering canvas is resized
  7591. */
  7592. this.onResizeObservable = new BABYLON.Observable();
  7593. /**
  7594. * Observable event triggered each time the canvas loses focus
  7595. */
  7596. this.onCanvasBlurObservable = new BABYLON.Observable();
  7597. /**
  7598. * Observable event triggered each time the canvas gains focus
  7599. */
  7600. this.onCanvasFocusObservable = new BABYLON.Observable();
  7601. /**
  7602. * Observable event triggered each time the canvas receives pointerout event
  7603. */
  7604. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7605. this._vrExclusivePointerMode = false;
  7606. // Uniform buffers list
  7607. this.disableUniformBuffers = false;
  7608. this._uniformBuffers = new Array();
  7609. this._windowIsBackground = false;
  7610. this._webGLVersion = 1.0;
  7611. this._badOS = false;
  7612. this._badDesktopOS = false;
  7613. this._colorWrite = true;
  7614. this._drawCalls = new BABYLON.PerfCounter();
  7615. this._renderingQueueLaunched = false;
  7616. this._activeRenderLoops = [];
  7617. // Deterministic lockstepMaxSteps
  7618. this._deterministicLockstep = false;
  7619. this._lockstepMaxSteps = 4;
  7620. // Lost context
  7621. this.onContextLostObservable = new BABYLON.Observable();
  7622. this.onContextRestoredObservable = new BABYLON.Observable();
  7623. this._contextWasLost = false;
  7624. this._doNotHandleContextLost = false;
  7625. // FPS
  7626. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7627. this._fps = 60;
  7628. this._deltaTime = 0;
  7629. /**
  7630. * Turn this value on if you want to pause FPS computation when in background
  7631. */
  7632. this.disablePerformanceMonitorInBackground = false;
  7633. // States
  7634. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7635. this._stencilState = new BABYLON.Internals._StencilState();
  7636. this._alphaState = new BABYLON.Internals._AlphaState();
  7637. this._alphaMode = Engine.ALPHA_DISABLE;
  7638. // Cache
  7639. this._internalTexturesCache = new Array();
  7640. this._maxTextureChannels = 16;
  7641. this._activeTexturesCache = {};
  7642. this._compiledEffects = {};
  7643. this._vertexAttribArraysEnabled = [];
  7644. this._uintIndicesCurrentlySet = false;
  7645. this._currentBoundBuffer = new Array();
  7646. this._currentBufferPointers = new Array();
  7647. this._currentInstanceLocations = new Array();
  7648. this._currentInstanceBuffers = new Array();
  7649. this._vaoRecordInProgress = false;
  7650. this._mustWipeVertexAttributes = false;
  7651. // Hardware supported Compressed Textures
  7652. this._texturesSupported = new Array();
  7653. this._onVRFullScreenTriggered = function () {
  7654. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7655. //get the old size before we change
  7656. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7657. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7658. //get the width and height, change the render size
  7659. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7660. var width, height;
  7661. _this.setHardwareScalingLevel(1);
  7662. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7663. }
  7664. else {
  7665. //When the specs are implemented, need to uncomment this.
  7666. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7667. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7668. _this._vrDisplayEnabled = undefined;
  7669. }
  7670. };
  7671. var canvas;
  7672. Engine.Instances.push(this);
  7673. options = options || {};
  7674. if (canvasOrContext.getContext) {
  7675. canvas = canvasOrContext;
  7676. this._renderingCanvas = canvas;
  7677. if (antialias != null) {
  7678. options.antialias = antialias;
  7679. }
  7680. if (options.deterministicLockstep === undefined) {
  7681. options.deterministicLockstep = false;
  7682. }
  7683. if (options.lockstepMaxSteps === undefined) {
  7684. options.lockstepMaxSteps = 4;
  7685. }
  7686. if (options.preserveDrawingBuffer === undefined) {
  7687. options.preserveDrawingBuffer = false;
  7688. }
  7689. if (options.audioEngine === undefined) {
  7690. options.audioEngine = true;
  7691. }
  7692. if (options.stencil === undefined) {
  7693. options.stencil = true;
  7694. }
  7695. this._deterministicLockstep = options.deterministicLockstep;
  7696. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7697. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7698. // GL
  7699. if (!options.disableWebGL2Support) {
  7700. try {
  7701. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7702. if (this._gl) {
  7703. this._webGLVersion = 2.0;
  7704. }
  7705. }
  7706. catch (e) {
  7707. // Do nothing
  7708. }
  7709. }
  7710. if (!this._gl) {
  7711. if (!canvas) {
  7712. throw new Error("The provided canvas is null or undefined.");
  7713. }
  7714. try {
  7715. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7716. }
  7717. catch (e) {
  7718. throw new Error("WebGL not supported");
  7719. }
  7720. }
  7721. if (!this._gl) {
  7722. throw new Error("WebGL not supported");
  7723. }
  7724. this._onCanvasFocus = function () {
  7725. _this.onCanvasFocusObservable.notifyObservers(_this);
  7726. };
  7727. this._onCanvasBlur = function () {
  7728. _this.onCanvasBlurObservable.notifyObservers(_this);
  7729. };
  7730. canvas.addEventListener("focus", this._onCanvasFocus);
  7731. canvas.addEventListener("blur", this._onCanvasBlur);
  7732. this._onBlur = function () {
  7733. if (_this.disablePerformanceMonitorInBackground) {
  7734. _this._performanceMonitor.disable();
  7735. }
  7736. _this._windowIsBackground = true;
  7737. };
  7738. this._onFocus = function () {
  7739. if (_this.disablePerformanceMonitorInBackground) {
  7740. _this._performanceMonitor.enable();
  7741. }
  7742. _this._windowIsBackground = false;
  7743. };
  7744. this._onCanvasPointerOut = function () {
  7745. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7746. };
  7747. window.addEventListener("blur", this._onBlur);
  7748. window.addEventListener("focus", this._onFocus);
  7749. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7750. // Context lost
  7751. if (!this._doNotHandleContextLost) {
  7752. this._onContextLost = function (evt) {
  7753. evt.preventDefault();
  7754. _this._contextWasLost = true;
  7755. BABYLON.Tools.Warn("WebGL context lost.");
  7756. _this.onContextLostObservable.notifyObservers(_this);
  7757. };
  7758. this._onContextRestored = function (evt) {
  7759. // Adding a timeout to avoid race condition at browser level
  7760. setTimeout(function () {
  7761. // Rebuild gl context
  7762. _this._initGLContext();
  7763. // Rebuild effects
  7764. _this._rebuildEffects();
  7765. // Rebuild textures
  7766. _this._rebuildInternalTextures();
  7767. // Rebuild buffers
  7768. _this._rebuildBuffers();
  7769. // Cache
  7770. _this.wipeCaches(true);
  7771. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7772. _this.onContextRestoredObservable.notifyObservers(_this);
  7773. _this._contextWasLost = false;
  7774. }, 0);
  7775. };
  7776. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7777. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7778. }
  7779. }
  7780. else {
  7781. this._gl = canvasOrContext;
  7782. this._renderingCanvas = this._gl.canvas;
  7783. if (this._gl.renderbufferStorageMultisample) {
  7784. this._webGLVersion = 2.0;
  7785. }
  7786. options.stencil = this._gl.getContextAttributes().stencil;
  7787. }
  7788. // Viewport
  7789. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7790. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7791. this.resize();
  7792. this._isStencilEnable = options.stencil;
  7793. this._initGLContext();
  7794. if (canvas) {
  7795. // Fullscreen
  7796. this._onFullscreenChange = function () {
  7797. if (document.fullscreen !== undefined) {
  7798. _this.isFullscreen = document.fullscreen;
  7799. }
  7800. else if (document.mozFullScreen !== undefined) {
  7801. _this.isFullscreen = document.mozFullScreen;
  7802. }
  7803. else if (document.webkitIsFullScreen !== undefined) {
  7804. _this.isFullscreen = document.webkitIsFullScreen;
  7805. }
  7806. else if (document.msIsFullScreen !== undefined) {
  7807. _this.isFullscreen = document.msIsFullScreen;
  7808. }
  7809. // Pointer lock
  7810. if (_this.isFullscreen && _this._pointerLockRequested) {
  7811. canvas.requestPointerLock = canvas.requestPointerLock ||
  7812. canvas.msRequestPointerLock ||
  7813. canvas.mozRequestPointerLock ||
  7814. canvas.webkitRequestPointerLock;
  7815. if (canvas.requestPointerLock) {
  7816. canvas.requestPointerLock();
  7817. }
  7818. }
  7819. };
  7820. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7821. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7822. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7823. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7824. // Pointer lock
  7825. this._onPointerLockChange = function () {
  7826. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7827. document.webkitPointerLockElement === canvas ||
  7828. document.msPointerLockElement === canvas ||
  7829. document.pointerLockElement === canvas);
  7830. };
  7831. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7832. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7833. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7834. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7835. this._onVRDisplayPointerRestricted = function () {
  7836. _this._vrExclusivePointerMode = true;
  7837. canvas.requestPointerLock();
  7838. };
  7839. this._onVRDisplayPointerUnrestricted = function () {
  7840. _this._vrExclusivePointerMode = false;
  7841. document.exitPointerLock();
  7842. };
  7843. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7844. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7845. }
  7846. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7847. Engine.audioEngine = new BABYLON.AudioEngine();
  7848. }
  7849. // Prepare buffer pointers
  7850. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7851. this._currentBufferPointers[i] = new BufferPointer();
  7852. }
  7853. // Load WebVR Devices
  7854. if (options.autoEnableWebVR) {
  7855. this.initWebVR();
  7856. }
  7857. // Detect if we are running on a faulty buggy OS.
  7858. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7859. // Detect if we are running on a faulty buggy desktop OS.
  7860. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7861. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7862. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7863. }
  7864. Object.defineProperty(Engine, "LastCreatedEngine", {
  7865. get: function () {
  7866. if (Engine.Instances.length === 0) {
  7867. return null;
  7868. }
  7869. return Engine.Instances[Engine.Instances.length - 1];
  7870. },
  7871. enumerable: true,
  7872. configurable: true
  7873. });
  7874. Object.defineProperty(Engine, "LastCreatedScene", {
  7875. get: function () {
  7876. var lastCreatedEngine = Engine.LastCreatedEngine;
  7877. if (!lastCreatedEngine) {
  7878. return null;
  7879. }
  7880. if (lastCreatedEngine.scenes.length === 0) {
  7881. return null;
  7882. }
  7883. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. /**
  7889. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7890. */
  7891. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7892. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7893. var engine = Engine.Instances[engineIndex];
  7894. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7895. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7896. }
  7897. }
  7898. };
  7899. Object.defineProperty(Engine, "NEVER", {
  7900. get: function () {
  7901. return Engine._NEVER;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(Engine, "ALWAYS", {
  7907. get: function () {
  7908. return Engine._ALWAYS;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Engine, "LESS", {
  7914. get: function () {
  7915. return Engine._LESS;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(Engine, "EQUAL", {
  7921. get: function () {
  7922. return Engine._EQUAL;
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. Object.defineProperty(Engine, "LEQUAL", {
  7928. get: function () {
  7929. return Engine._LEQUAL;
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. Object.defineProperty(Engine, "GREATER", {
  7935. get: function () {
  7936. return Engine._GREATER;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. Object.defineProperty(Engine, "GEQUAL", {
  7942. get: function () {
  7943. return Engine._GEQUAL;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. Object.defineProperty(Engine, "NOTEQUAL", {
  7949. get: function () {
  7950. return Engine._NOTEQUAL;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(Engine, "KEEP", {
  7956. get: function () {
  7957. return Engine._KEEP;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. Object.defineProperty(Engine, "REPLACE", {
  7963. get: function () {
  7964. return Engine._REPLACE;
  7965. },
  7966. enumerable: true,
  7967. configurable: true
  7968. });
  7969. Object.defineProperty(Engine, "INCR", {
  7970. get: function () {
  7971. return Engine._INCR;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(Engine, "DECR", {
  7977. get: function () {
  7978. return Engine._DECR;
  7979. },
  7980. enumerable: true,
  7981. configurable: true
  7982. });
  7983. Object.defineProperty(Engine, "INVERT", {
  7984. get: function () {
  7985. return Engine._INVERT;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Object.defineProperty(Engine, "INCR_WRAP", {
  7991. get: function () {
  7992. return Engine._INCR_WRAP;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. Object.defineProperty(Engine, "DECR_WRAP", {
  7998. get: function () {
  7999. return Engine._DECR_WRAP;
  8000. },
  8001. enumerable: true,
  8002. configurable: true
  8003. });
  8004. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8005. get: function () {
  8006. return Engine._ALPHA_DISABLE;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8012. get: function () {
  8013. return Engine._ALPHA_ONEONE;
  8014. },
  8015. enumerable: true,
  8016. configurable: true
  8017. });
  8018. Object.defineProperty(Engine, "ALPHA_ADD", {
  8019. get: function () {
  8020. return Engine._ALPHA_ADD;
  8021. },
  8022. enumerable: true,
  8023. configurable: true
  8024. });
  8025. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8026. get: function () {
  8027. return Engine._ALPHA_COMBINE;
  8028. },
  8029. enumerable: true,
  8030. configurable: true
  8031. });
  8032. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8033. get: function () {
  8034. return Engine._ALPHA_SUBTRACT;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8040. get: function () {
  8041. return Engine._ALPHA_MULTIPLY;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8047. get: function () {
  8048. return Engine._ALPHA_MAXIMIZED;
  8049. },
  8050. enumerable: true,
  8051. configurable: true
  8052. });
  8053. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8054. get: function () {
  8055. return Engine._ALPHA_PREMULTIPLIED;
  8056. },
  8057. enumerable: true,
  8058. configurable: true
  8059. });
  8060. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8061. get: function () {
  8062. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8063. },
  8064. enumerable: true,
  8065. configurable: true
  8066. });
  8067. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8068. get: function () {
  8069. return Engine._ALPHA_INTERPOLATE;
  8070. },
  8071. enumerable: true,
  8072. configurable: true
  8073. });
  8074. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8075. get: function () {
  8076. return Engine._ALPHA_SCREENMODE;
  8077. },
  8078. enumerable: true,
  8079. configurable: true
  8080. });
  8081. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8082. get: function () {
  8083. return Engine._DELAYLOADSTATE_NONE;
  8084. },
  8085. enumerable: true,
  8086. configurable: true
  8087. });
  8088. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8089. get: function () {
  8090. return Engine._DELAYLOADSTATE_LOADED;
  8091. },
  8092. enumerable: true,
  8093. configurable: true
  8094. });
  8095. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8096. get: function () {
  8097. return Engine._DELAYLOADSTATE_LOADING;
  8098. },
  8099. enumerable: true,
  8100. configurable: true
  8101. });
  8102. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8103. get: function () {
  8104. return Engine._DELAYLOADSTATE_NOTLOADED;
  8105. },
  8106. enumerable: true,
  8107. configurable: true
  8108. });
  8109. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8110. get: function () {
  8111. return Engine._TEXTUREFORMAT_ALPHA;
  8112. },
  8113. enumerable: true,
  8114. configurable: true
  8115. });
  8116. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8117. get: function () {
  8118. return Engine._TEXTUREFORMAT_LUMINANCE;
  8119. },
  8120. enumerable: true,
  8121. configurable: true
  8122. });
  8123. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8124. get: function () {
  8125. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8126. },
  8127. enumerable: true,
  8128. configurable: true
  8129. });
  8130. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8131. get: function () {
  8132. return Engine._TEXTUREFORMAT_RGB;
  8133. },
  8134. enumerable: true,
  8135. configurable: true
  8136. });
  8137. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8138. get: function () {
  8139. return Engine._TEXTUREFORMAT_RGBA;
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8145. get: function () {
  8146. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8147. },
  8148. enumerable: true,
  8149. configurable: true
  8150. });
  8151. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8152. get: function () {
  8153. return Engine._TEXTURETYPE_FLOAT;
  8154. },
  8155. enumerable: true,
  8156. configurable: true
  8157. });
  8158. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8159. get: function () {
  8160. return Engine._TEXTURETYPE_HALF_FLOAT;
  8161. },
  8162. enumerable: true,
  8163. configurable: true
  8164. });
  8165. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8166. get: function () {
  8167. return Engine._SCALEMODE_FLOOR;
  8168. },
  8169. enumerable: true,
  8170. configurable: true
  8171. });
  8172. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8173. get: function () {
  8174. return Engine._SCALEMODE_NEAREST;
  8175. },
  8176. enumerable: true,
  8177. configurable: true
  8178. });
  8179. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8180. get: function () {
  8181. return Engine._SCALEMODE_CEILING;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. Object.defineProperty(Engine, "Version", {
  8187. get: function () {
  8188. return "3.1-alpha";
  8189. },
  8190. enumerable: true,
  8191. configurable: true
  8192. });
  8193. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8194. get: function () {
  8195. return this._vrExclusivePointerMode;
  8196. },
  8197. enumerable: true,
  8198. configurable: true
  8199. });
  8200. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8201. get: function () {
  8202. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8203. },
  8204. enumerable: true,
  8205. configurable: true
  8206. });
  8207. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8208. get: function () {
  8209. return this._webGLVersion < 2 || this.forcePOTTextures;
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214. Object.defineProperty(Engine.prototype, "badOS", {
  8215. get: function () {
  8216. return this._badOS;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8222. get: function () {
  8223. return this._badDesktopOS;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8229. get: function () {
  8230. return this._performanceMonitor;
  8231. },
  8232. enumerable: true,
  8233. configurable: true
  8234. });
  8235. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8236. get: function () {
  8237. return this._texturesSupported;
  8238. },
  8239. enumerable: true,
  8240. configurable: true
  8241. });
  8242. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8243. get: function () {
  8244. return this._textureFormatInUse;
  8245. },
  8246. enumerable: true,
  8247. configurable: true
  8248. });
  8249. Object.defineProperty(Engine.prototype, "currentViewport", {
  8250. get: function () {
  8251. return this._cachedViewport;
  8252. },
  8253. enumerable: true,
  8254. configurable: true
  8255. });
  8256. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8257. // Empty texture
  8258. get: function () {
  8259. if (!this._emptyTexture) {
  8260. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8261. }
  8262. return this._emptyTexture;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8268. get: function () {
  8269. if (!this._emptyCubeTexture) {
  8270. var faceData = new Uint8Array(4);
  8271. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8272. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8273. }
  8274. return this._emptyCubeTexture;
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. Engine.prototype._rebuildInternalTextures = function () {
  8280. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8281. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8282. var internalTexture = currentState_1[_i];
  8283. internalTexture._rebuild();
  8284. }
  8285. };
  8286. Engine.prototype._rebuildEffects = function () {
  8287. for (var key in this._compiledEffects) {
  8288. var effect = this._compiledEffects[key];
  8289. effect._prepareEffect();
  8290. }
  8291. BABYLON.Effect.ResetCache();
  8292. };
  8293. Engine.prototype._rebuildBuffers = function () {
  8294. // Index / Vertex
  8295. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8296. var scene = _a[_i];
  8297. scene.resetCachedMaterial();
  8298. scene._rebuildGeometries();
  8299. scene._rebuildTextures();
  8300. }
  8301. // Uniforms
  8302. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8303. var uniformBuffer = _c[_b];
  8304. uniformBuffer._rebuild();
  8305. }
  8306. };
  8307. Engine.prototype._initGLContext = function () {
  8308. // Caps
  8309. this._caps = new EngineCapabilities();
  8310. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8311. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8312. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8313. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8314. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8315. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8316. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8317. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8318. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8319. // Infos
  8320. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8321. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8322. if (rendererInfo != null) {
  8323. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8324. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8325. }
  8326. if (!this._glVendor) {
  8327. this._glVendor = "Unknown vendor";
  8328. }
  8329. if (!this._glRenderer) {
  8330. this._glRenderer = "Unknown renderer";
  8331. }
  8332. // Constants
  8333. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8334. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8335. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8336. this._gl.DEPTH24_STENCIL8 = 35056;
  8337. // Extensions
  8338. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8339. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8340. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8341. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8342. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8343. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8344. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8345. 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');
  8346. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8347. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8348. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8349. this._caps.highPrecisionShaderSupported = true;
  8350. // Checks if some of the format renders first to allow the use of webgl inspector.
  8351. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8352. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8353. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8354. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8355. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8356. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8357. if (this._webGLVersion > 1) {
  8358. this._gl.HALF_FLOAT_OES = 0x140B;
  8359. }
  8360. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8361. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8362. // Draw buffers
  8363. if (this._webGLVersion > 1) {
  8364. this._caps.drawBuffersExtension = true;
  8365. }
  8366. else {
  8367. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8368. if (drawBuffersExtension !== null) {
  8369. this._caps.drawBuffersExtension = true;
  8370. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8371. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8372. for (var i = 0; i < 16; i++) {
  8373. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8374. }
  8375. }
  8376. else {
  8377. this._caps.drawBuffersExtension = false;
  8378. }
  8379. }
  8380. // Depth Texture
  8381. if (this._webGLVersion > 1) {
  8382. this._caps.depthTextureExtension = true;
  8383. }
  8384. else {
  8385. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8386. if (depthTextureExtension != null) {
  8387. this._caps.depthTextureExtension = true;
  8388. }
  8389. }
  8390. // Vertex array object
  8391. if (this._webGLVersion > 1) {
  8392. this._caps.vertexArrayObject = true;
  8393. }
  8394. else {
  8395. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8396. if (vertexArrayObjectExtension != null) {
  8397. this._caps.vertexArrayObject = true;
  8398. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8399. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8400. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8401. }
  8402. else {
  8403. this._caps.vertexArrayObject = false;
  8404. }
  8405. }
  8406. // Instances count
  8407. if (this._webGLVersion > 1) {
  8408. this._caps.instancedArrays = true;
  8409. }
  8410. else {
  8411. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8412. if (instanceExtension != null) {
  8413. this._caps.instancedArrays = true;
  8414. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8415. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8416. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8417. }
  8418. else {
  8419. this._caps.instancedArrays = false;
  8420. }
  8421. }
  8422. // Intelligently add supported compressed formats in order to check for.
  8423. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8424. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8425. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8426. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8427. if (this._caps.astc)
  8428. this.texturesSupported.push('-astc.ktx');
  8429. if (this._caps.s3tc)
  8430. this.texturesSupported.push('-dxt.ktx');
  8431. if (this._caps.pvrtc)
  8432. this.texturesSupported.push('-pvrtc.ktx');
  8433. if (this._caps.etc2)
  8434. this.texturesSupported.push('-etc2.ktx');
  8435. if (this._caps.etc1)
  8436. this.texturesSupported.push('-etc1.ktx');
  8437. if (this._gl.getShaderPrecisionFormat) {
  8438. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8439. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8440. }
  8441. // Depth buffer
  8442. this.setDepthBuffer(true);
  8443. this.setDepthFunctionToLessOrEqual();
  8444. this.setDepthWrite(true);
  8445. };
  8446. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8447. get: function () {
  8448. return this._webGLVersion;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8454. /**
  8455. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8456. */
  8457. get: function () {
  8458. return this._isStencilEnable;
  8459. },
  8460. enumerable: true,
  8461. configurable: true
  8462. });
  8463. Engine.prototype._prepareWorkingCanvas = function () {
  8464. if (this._workingCanvas) {
  8465. return;
  8466. }
  8467. this._workingCanvas = document.createElement("canvas");
  8468. this._workingContext = this._workingCanvas.getContext("2d");
  8469. };
  8470. Engine.prototype.resetTextureCache = function () {
  8471. for (var key in this._activeTexturesCache) {
  8472. this._activeTexturesCache[key] = null;
  8473. }
  8474. };
  8475. Engine.prototype.isDeterministicLockStep = function () {
  8476. return this._deterministicLockstep;
  8477. };
  8478. Engine.prototype.getLockstepMaxSteps = function () {
  8479. return this._lockstepMaxSteps;
  8480. };
  8481. Engine.prototype.getGlInfo = function () {
  8482. return {
  8483. vendor: this._glVendor,
  8484. renderer: this._glRenderer,
  8485. version: this._glVersion
  8486. };
  8487. };
  8488. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8489. if (useScreen === void 0) { useScreen = false; }
  8490. var viewport = camera.viewport;
  8491. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8492. };
  8493. Engine.prototype.getRenderWidth = function (useScreen) {
  8494. if (useScreen === void 0) { useScreen = false; }
  8495. if (!useScreen && this._currentRenderTarget) {
  8496. return this._currentRenderTarget.width;
  8497. }
  8498. return this._gl.drawingBufferWidth;
  8499. };
  8500. Engine.prototype.getRenderHeight = function (useScreen) {
  8501. if (useScreen === void 0) { useScreen = false; }
  8502. if (!useScreen && this._currentRenderTarget) {
  8503. return this._currentRenderTarget.height;
  8504. }
  8505. return this._gl.drawingBufferHeight;
  8506. };
  8507. Engine.prototype.getRenderingCanvas = function () {
  8508. return this._renderingCanvas;
  8509. };
  8510. Engine.prototype.getRenderingCanvasClientRect = function () {
  8511. return this._renderingCanvas.getBoundingClientRect();
  8512. };
  8513. Engine.prototype.setHardwareScalingLevel = function (level) {
  8514. this._hardwareScalingLevel = level;
  8515. this.resize();
  8516. };
  8517. Engine.prototype.getHardwareScalingLevel = function () {
  8518. return this._hardwareScalingLevel;
  8519. };
  8520. Engine.prototype.getLoadedTexturesCache = function () {
  8521. return this._internalTexturesCache;
  8522. };
  8523. Engine.prototype.getCaps = function () {
  8524. return this._caps;
  8525. };
  8526. Object.defineProperty(Engine.prototype, "drawCalls", {
  8527. /** The number of draw calls submitted last frame */
  8528. get: function () {
  8529. return this._drawCalls.current;
  8530. },
  8531. enumerable: true,
  8532. configurable: true
  8533. });
  8534. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8535. get: function () {
  8536. return this._drawCalls;
  8537. },
  8538. enumerable: true,
  8539. configurable: true
  8540. });
  8541. Engine.prototype.getDepthFunction = function () {
  8542. return this._depthCullingState.depthFunc;
  8543. };
  8544. Engine.prototype.setDepthFunction = function (depthFunc) {
  8545. this._depthCullingState.depthFunc = depthFunc;
  8546. };
  8547. Engine.prototype.setDepthFunctionToGreater = function () {
  8548. this._depthCullingState.depthFunc = this._gl.GREATER;
  8549. };
  8550. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8551. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8552. };
  8553. Engine.prototype.setDepthFunctionToLess = function () {
  8554. this._depthCullingState.depthFunc = this._gl.LESS;
  8555. };
  8556. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8557. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8558. };
  8559. Engine.prototype.getStencilBuffer = function () {
  8560. return this._stencilState.stencilTest;
  8561. };
  8562. Engine.prototype.setStencilBuffer = function (enable) {
  8563. this._stencilState.stencilTest = enable;
  8564. };
  8565. Engine.prototype.getStencilMask = function () {
  8566. return this._stencilState.stencilMask;
  8567. };
  8568. Engine.prototype.setStencilMask = function (mask) {
  8569. this._stencilState.stencilMask = mask;
  8570. };
  8571. Engine.prototype.getStencilFunction = function () {
  8572. return this._stencilState.stencilFunc;
  8573. };
  8574. Engine.prototype.getStencilFunctionReference = function () {
  8575. return this._stencilState.stencilFuncRef;
  8576. };
  8577. Engine.prototype.getStencilFunctionMask = function () {
  8578. return this._stencilState.stencilFuncMask;
  8579. };
  8580. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8581. this._stencilState.stencilFunc = stencilFunc;
  8582. };
  8583. Engine.prototype.setStencilFunctionReference = function (reference) {
  8584. this._stencilState.stencilFuncRef = reference;
  8585. };
  8586. Engine.prototype.setStencilFunctionMask = function (mask) {
  8587. this._stencilState.stencilFuncMask = mask;
  8588. };
  8589. Engine.prototype.getStencilOperationFail = function () {
  8590. return this._stencilState.stencilOpStencilFail;
  8591. };
  8592. Engine.prototype.getStencilOperationDepthFail = function () {
  8593. return this._stencilState.stencilOpDepthFail;
  8594. };
  8595. Engine.prototype.getStencilOperationPass = function () {
  8596. return this._stencilState.stencilOpStencilDepthPass;
  8597. };
  8598. Engine.prototype.setStencilOperationFail = function (operation) {
  8599. this._stencilState.stencilOpStencilFail = operation;
  8600. };
  8601. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8602. this._stencilState.stencilOpDepthFail = operation;
  8603. };
  8604. Engine.prototype.setStencilOperationPass = function (operation) {
  8605. this._stencilState.stencilOpStencilDepthPass = operation;
  8606. };
  8607. Engine.prototype.setDitheringState = function (value) {
  8608. if (value) {
  8609. this._gl.enable(this._gl.DITHER);
  8610. }
  8611. else {
  8612. this._gl.disable(this._gl.DITHER);
  8613. }
  8614. };
  8615. /**
  8616. * stop executing a render loop function and remove it from the execution array
  8617. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8618. */
  8619. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8620. if (!renderFunction) {
  8621. this._activeRenderLoops = [];
  8622. return;
  8623. }
  8624. var index = this._activeRenderLoops.indexOf(renderFunction);
  8625. if (index >= 0) {
  8626. this._activeRenderLoops.splice(index, 1);
  8627. }
  8628. };
  8629. Engine.prototype._renderLoop = function () {
  8630. if (!this._contextWasLost) {
  8631. var shouldRender = true;
  8632. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8633. shouldRender = false;
  8634. }
  8635. if (shouldRender) {
  8636. // Start new frame
  8637. this.beginFrame();
  8638. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8639. var renderFunction = this._activeRenderLoops[index];
  8640. renderFunction();
  8641. }
  8642. // Present
  8643. this.endFrame();
  8644. }
  8645. }
  8646. if (this._activeRenderLoops.length > 0) {
  8647. // Register new frame
  8648. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8649. }
  8650. else {
  8651. this._renderingQueueLaunched = false;
  8652. }
  8653. };
  8654. /**
  8655. * Register and execute a render loop. The engine can have more than one render function.
  8656. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8657. * @example
  8658. * engine.runRenderLoop(function () {
  8659. * scene.render()
  8660. * })
  8661. */
  8662. Engine.prototype.runRenderLoop = function (renderFunction) {
  8663. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8664. return;
  8665. }
  8666. this._activeRenderLoops.push(renderFunction);
  8667. if (!this._renderingQueueLaunched) {
  8668. this._renderingQueueLaunched = true;
  8669. this._bindedRenderFunction = this._renderLoop.bind(this);
  8670. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8671. }
  8672. };
  8673. /**
  8674. * Toggle full screen mode.
  8675. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8676. * @param {any} options - an options object to be sent to the requestFullscreen function
  8677. */
  8678. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8679. if (this.isFullscreen) {
  8680. BABYLON.Tools.ExitFullscreen();
  8681. }
  8682. else {
  8683. this._pointerLockRequested = requestPointerLock;
  8684. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8685. }
  8686. };
  8687. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8688. if (stencil === void 0) { stencil = false; }
  8689. this.applyStates();
  8690. var mode = 0;
  8691. if (backBuffer && color) {
  8692. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8693. mode |= this._gl.COLOR_BUFFER_BIT;
  8694. }
  8695. if (depth) {
  8696. this._gl.clearDepth(1.0);
  8697. mode |= this._gl.DEPTH_BUFFER_BIT;
  8698. }
  8699. if (stencil) {
  8700. this._gl.clearStencil(0);
  8701. mode |= this._gl.STENCIL_BUFFER_BIT;
  8702. }
  8703. this._gl.clear(mode);
  8704. };
  8705. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8706. var gl = this._gl;
  8707. // Save state
  8708. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8709. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8710. // Change state
  8711. gl.enable(gl.SCISSOR_TEST);
  8712. gl.scissor(x, y, width, height);
  8713. // Clear
  8714. this.clear(clearColor, true, true, true);
  8715. // Restore state
  8716. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8717. if (curScissor === true) {
  8718. gl.enable(gl.SCISSOR_TEST);
  8719. }
  8720. else {
  8721. gl.disable(gl.SCISSOR_TEST);
  8722. }
  8723. };
  8724. /**
  8725. * Set the WebGL's viewport
  8726. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8727. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8728. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8729. */
  8730. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8731. var width = requiredWidth || this.getRenderWidth();
  8732. var height = requiredHeight || this.getRenderHeight();
  8733. var x = viewport.x || 0;
  8734. var y = viewport.y || 0;
  8735. this._cachedViewport = viewport;
  8736. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8737. };
  8738. /**
  8739. * Directly set the WebGL Viewport
  8740. * The x, y, width & height are directly passed to the WebGL call
  8741. * @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.
  8742. */
  8743. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8744. var currentViewport = this._cachedViewport;
  8745. this._cachedViewport = null;
  8746. this._gl.viewport(x, y, width, height);
  8747. return currentViewport;
  8748. };
  8749. Engine.prototype.beginFrame = function () {
  8750. this._measureFps();
  8751. };
  8752. Engine.prototype.endFrame = function () {
  8753. //force a flush in case we are using a bad OS.
  8754. if (this._badOS) {
  8755. this.flushFramebuffer();
  8756. }
  8757. //submit frame to the vr device, if enabled
  8758. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8759. this._vrDisplayEnabled.submitFrame();
  8760. }
  8761. };
  8762. /**
  8763. * resize the view according to the canvas' size.
  8764. * @example
  8765. * window.addEventListener("resize", function () {
  8766. * engine.resize();
  8767. * });
  8768. */
  8769. Engine.prototype.resize = function () {
  8770. // We're not resizing the size of the canvas while in VR mode & presenting
  8771. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8772. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8773. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8774. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8775. }
  8776. };
  8777. /**
  8778. * force a specific size of the canvas
  8779. * @param {number} width - the new canvas' width
  8780. * @param {number} height - the new canvas' height
  8781. */
  8782. Engine.prototype.setSize = function (width, height) {
  8783. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8784. return;
  8785. }
  8786. this._renderingCanvas.width = width;
  8787. this._renderingCanvas.height = height;
  8788. for (var index = 0; index < this.scenes.length; index++) {
  8789. var scene = this.scenes[index];
  8790. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8791. var cam = scene.cameras[camIndex];
  8792. cam._currentRenderId = 0;
  8793. }
  8794. }
  8795. if (this.onResizeObservable.hasObservers) {
  8796. this.onResizeObservable.notifyObservers(this);
  8797. }
  8798. };
  8799. //WebVR functions
  8800. Engine.prototype.isVRDevicePresent = function (callback) {
  8801. this.getVRDevice(null, function (device) {
  8802. callback(device !== null);
  8803. });
  8804. };
  8805. Engine.prototype.getVRDevice = function (name, callback) {
  8806. if (!this.vrDisplaysPromise) {
  8807. callback(null);
  8808. return;
  8809. }
  8810. this.vrDisplaysPromise.then(function (devices) {
  8811. if (devices.length > 0) {
  8812. if (name) {
  8813. var found = devices.some(function (device) {
  8814. if (device.displayName === name) {
  8815. callback(device);
  8816. return true;
  8817. }
  8818. else {
  8819. return false;
  8820. }
  8821. });
  8822. if (!found) {
  8823. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8824. callback(devices[0]);
  8825. }
  8826. }
  8827. else {
  8828. //choose the first one
  8829. callback(devices[0]);
  8830. }
  8831. }
  8832. else {
  8833. BABYLON.Tools.Error("No WebVR devices found!");
  8834. callback(null);
  8835. }
  8836. });
  8837. };
  8838. Engine.prototype.initWebVR = function () {
  8839. if (!this.vrDisplaysPromise) {
  8840. this._getVRDisplays();
  8841. }
  8842. };
  8843. Engine.prototype.enableVR = function (vrDevice) {
  8844. this._vrDisplayEnabled = vrDevice;
  8845. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8846. };
  8847. Engine.prototype.disableVR = function () {
  8848. if (this._vrDisplayEnabled) {
  8849. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8850. }
  8851. };
  8852. Engine.prototype._getVRDisplays = function () {
  8853. var _this = this;
  8854. var getWebVRDevices = function (devices) {
  8855. _this._vrDisplays = devices.filter(function (device) {
  8856. return device instanceof VRDisplay;
  8857. });
  8858. return _this._vrDisplays;
  8859. };
  8860. if (navigator.getVRDisplays) {
  8861. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8862. }
  8863. };
  8864. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8865. if (this._currentRenderTarget) {
  8866. this.unBindFramebuffer(this._currentRenderTarget);
  8867. }
  8868. this._currentRenderTarget = texture;
  8869. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8870. var gl = this._gl;
  8871. if (texture.isCube) {
  8872. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8873. }
  8874. if (this._cachedViewport && !forceFullscreenViewport) {
  8875. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8876. }
  8877. else {
  8878. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8879. }
  8880. this.wipeCaches();
  8881. };
  8882. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8883. if (this._currentFramebuffer !== framebuffer) {
  8884. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8885. this._currentFramebuffer = framebuffer;
  8886. }
  8887. };
  8888. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8889. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8890. this._currentRenderTarget = null;
  8891. // If MSAA, we need to bitblt back to main texture
  8892. var gl = this._gl;
  8893. if (texture._MSAAFramebuffer) {
  8894. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8895. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8896. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8897. }
  8898. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8899. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8900. gl.generateMipmap(gl.TEXTURE_2D);
  8901. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8902. }
  8903. if (onBeforeUnbind) {
  8904. if (texture._MSAAFramebuffer) {
  8905. // Bind the correct framebuffer
  8906. this.bindUnboundFramebuffer(texture._framebuffer);
  8907. }
  8908. onBeforeUnbind();
  8909. }
  8910. this.bindUnboundFramebuffer(null);
  8911. };
  8912. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8913. if (texture.generateMipMaps) {
  8914. var gl = this._gl;
  8915. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8916. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8917. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8918. }
  8919. };
  8920. Engine.prototype.flushFramebuffer = function () {
  8921. this._gl.flush();
  8922. };
  8923. Engine.prototype.restoreDefaultFramebuffer = function () {
  8924. if (this._currentRenderTarget) {
  8925. this.unBindFramebuffer(this._currentRenderTarget);
  8926. }
  8927. else {
  8928. this.bindUnboundFramebuffer(null);
  8929. }
  8930. if (this._cachedViewport) {
  8931. this.setViewport(this._cachedViewport);
  8932. }
  8933. this.wipeCaches();
  8934. };
  8935. // UBOs
  8936. Engine.prototype.createUniformBuffer = function (elements) {
  8937. var ubo = this._gl.createBuffer();
  8938. this.bindUniformBuffer(ubo);
  8939. if (elements instanceof Float32Array) {
  8940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8941. }
  8942. else {
  8943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8944. }
  8945. this.bindUniformBuffer(null);
  8946. ubo.references = 1;
  8947. return ubo;
  8948. };
  8949. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8950. var ubo = this._gl.createBuffer();
  8951. this.bindUniformBuffer(ubo);
  8952. if (elements instanceof Float32Array) {
  8953. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8954. }
  8955. else {
  8956. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8957. }
  8958. this.bindUniformBuffer(null);
  8959. ubo.references = 1;
  8960. return ubo;
  8961. };
  8962. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8963. this.bindUniformBuffer(uniformBuffer);
  8964. if (offset === undefined) {
  8965. offset = 0;
  8966. }
  8967. if (count === undefined) {
  8968. if (elements instanceof Float32Array) {
  8969. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8970. }
  8971. else {
  8972. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8973. }
  8974. }
  8975. else {
  8976. if (elements instanceof Float32Array) {
  8977. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8978. }
  8979. else {
  8980. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8981. }
  8982. }
  8983. this.bindUniformBuffer(null);
  8984. };
  8985. // VBOs
  8986. Engine.prototype._resetVertexBufferBinding = function () {
  8987. this.bindArrayBuffer(null);
  8988. this._cachedVertexBuffers = null;
  8989. };
  8990. Engine.prototype.createVertexBuffer = function (vertices) {
  8991. var vbo = this._gl.createBuffer();
  8992. this.bindArrayBuffer(vbo);
  8993. if (vertices instanceof Float32Array) {
  8994. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8995. }
  8996. else {
  8997. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8998. }
  8999. this._resetVertexBufferBinding();
  9000. vbo.references = 1;
  9001. return vbo;
  9002. };
  9003. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9004. var vbo = this._gl.createBuffer();
  9005. this.bindArrayBuffer(vbo);
  9006. if (vertices instanceof Float32Array) {
  9007. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9008. }
  9009. else {
  9010. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9011. }
  9012. this._resetVertexBufferBinding();
  9013. vbo.references = 1;
  9014. return vbo;
  9015. };
  9016. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9017. this.bindArrayBuffer(vertexBuffer);
  9018. if (offset === undefined) {
  9019. offset = 0;
  9020. }
  9021. if (count === undefined) {
  9022. if (vertices instanceof Float32Array) {
  9023. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9024. }
  9025. else {
  9026. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9027. }
  9028. }
  9029. else {
  9030. if (vertices instanceof Float32Array) {
  9031. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9032. }
  9033. else {
  9034. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9035. }
  9036. }
  9037. this._resetVertexBufferBinding();
  9038. };
  9039. Engine.prototype._resetIndexBufferBinding = function () {
  9040. this.bindIndexBuffer(null);
  9041. this._cachedIndexBuffer = null;
  9042. };
  9043. Engine.prototype.createIndexBuffer = function (indices) {
  9044. var vbo = this._gl.createBuffer();
  9045. this.bindIndexBuffer(vbo);
  9046. // Check for 32 bits indices
  9047. var arrayBuffer;
  9048. var need32Bits = false;
  9049. if (indices instanceof Uint16Array) {
  9050. arrayBuffer = indices;
  9051. }
  9052. else {
  9053. //check 32 bit support
  9054. if (this._caps.uintIndices) {
  9055. if (indices instanceof Uint32Array) {
  9056. arrayBuffer = indices;
  9057. need32Bits = true;
  9058. }
  9059. else {
  9060. //number[] or Int32Array, check if 32 bit is necessary
  9061. for (var index = 0; index < indices.length; index++) {
  9062. if (indices[index] > 65535) {
  9063. need32Bits = true;
  9064. break;
  9065. }
  9066. }
  9067. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9068. }
  9069. }
  9070. else {
  9071. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9072. arrayBuffer = new Uint16Array(indices);
  9073. }
  9074. }
  9075. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9076. this._resetIndexBufferBinding();
  9077. vbo.references = 1;
  9078. vbo.is32Bits = need32Bits;
  9079. return vbo;
  9080. };
  9081. Engine.prototype.bindArrayBuffer = function (buffer) {
  9082. if (!this._vaoRecordInProgress) {
  9083. this._unbindVertexArrayObject();
  9084. }
  9085. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9086. };
  9087. Engine.prototype.bindUniformBuffer = function (buffer) {
  9088. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9089. };
  9090. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9091. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9092. };
  9093. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9094. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9095. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9096. };
  9097. ;
  9098. Engine.prototype.bindIndexBuffer = function (buffer) {
  9099. if (!this._vaoRecordInProgress) {
  9100. this._unbindVertexArrayObject();
  9101. }
  9102. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9103. };
  9104. Engine.prototype.bindBuffer = function (buffer, target) {
  9105. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9106. this._gl.bindBuffer(target, buffer);
  9107. this._currentBoundBuffer[target] = buffer;
  9108. }
  9109. };
  9110. Engine.prototype.updateArrayBuffer = function (data) {
  9111. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9112. };
  9113. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9114. var pointer = this._currentBufferPointers[indx];
  9115. var changed = false;
  9116. if (!pointer.active) {
  9117. changed = true;
  9118. pointer.active = true;
  9119. pointer.index = indx;
  9120. pointer.size = size;
  9121. pointer.type = type;
  9122. pointer.normalized = normalized;
  9123. pointer.stride = stride;
  9124. pointer.offset = offset;
  9125. pointer.buffer = buffer;
  9126. }
  9127. else {
  9128. if (pointer.buffer !== buffer) {
  9129. pointer.buffer = buffer;
  9130. changed = true;
  9131. }
  9132. if (pointer.size !== size) {
  9133. pointer.size = size;
  9134. changed = true;
  9135. }
  9136. if (pointer.type !== type) {
  9137. pointer.type = type;
  9138. changed = true;
  9139. }
  9140. if (pointer.normalized !== normalized) {
  9141. pointer.normalized = normalized;
  9142. changed = true;
  9143. }
  9144. if (pointer.stride !== stride) {
  9145. pointer.stride = stride;
  9146. changed = true;
  9147. }
  9148. if (pointer.offset !== offset) {
  9149. pointer.offset = offset;
  9150. changed = true;
  9151. }
  9152. }
  9153. if (changed || this._vaoRecordInProgress) {
  9154. this.bindArrayBuffer(buffer);
  9155. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9156. }
  9157. };
  9158. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9159. if (indexBuffer == null) {
  9160. return;
  9161. }
  9162. if (this._cachedIndexBuffer !== indexBuffer) {
  9163. this._cachedIndexBuffer = indexBuffer;
  9164. this.bindIndexBuffer(indexBuffer);
  9165. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9166. }
  9167. };
  9168. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9169. var attributes = effect.getAttributesNames();
  9170. if (!this._vaoRecordInProgress) {
  9171. this._unbindVertexArrayObject();
  9172. }
  9173. this.unbindAllAttributes();
  9174. for (var index = 0; index < attributes.length; index++) {
  9175. var order = effect.getAttributeLocation(index);
  9176. if (order >= 0) {
  9177. var vertexBuffer = vertexBuffers[attributes[index]];
  9178. if (!vertexBuffer) {
  9179. continue;
  9180. }
  9181. this._gl.enableVertexAttribArray(order);
  9182. if (!this._vaoRecordInProgress) {
  9183. this._vertexAttribArraysEnabled[order] = true;
  9184. }
  9185. var buffer = vertexBuffer.getBuffer();
  9186. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9187. if (vertexBuffer.getIsInstanced()) {
  9188. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9189. if (!this._vaoRecordInProgress) {
  9190. this._currentInstanceLocations.push(order);
  9191. this._currentInstanceBuffers.push(buffer);
  9192. }
  9193. }
  9194. }
  9195. }
  9196. };
  9197. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9198. var vao = this._gl.createVertexArray();
  9199. this._vaoRecordInProgress = true;
  9200. this._gl.bindVertexArray(vao);
  9201. this._mustWipeVertexAttributes = true;
  9202. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9203. this.bindIndexBuffer(indexBuffer);
  9204. this._vaoRecordInProgress = false;
  9205. this._gl.bindVertexArray(null);
  9206. return vao;
  9207. };
  9208. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9209. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9210. this._cachedVertexArrayObject = vertexArrayObject;
  9211. this._gl.bindVertexArray(vertexArrayObject);
  9212. this._cachedVertexBuffers = null;
  9213. this._cachedIndexBuffer = null;
  9214. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9215. this._mustWipeVertexAttributes = true;
  9216. }
  9217. };
  9218. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9219. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9220. this._cachedVertexBuffers = vertexBuffer;
  9221. this._cachedEffectForVertexBuffers = effect;
  9222. var attributesCount = effect.getAttributesCount();
  9223. this._unbindVertexArrayObject();
  9224. this.unbindAllAttributes();
  9225. var offset = 0;
  9226. for (var index = 0; index < attributesCount; index++) {
  9227. if (index < vertexDeclaration.length) {
  9228. var order = effect.getAttributeLocation(index);
  9229. if (order >= 0) {
  9230. this._gl.enableVertexAttribArray(order);
  9231. this._vertexAttribArraysEnabled[order] = true;
  9232. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9233. }
  9234. offset += vertexDeclaration[index] * 4;
  9235. }
  9236. }
  9237. }
  9238. this._bindIndexBufferWithCache(indexBuffer);
  9239. };
  9240. Engine.prototype._unbindVertexArrayObject = function () {
  9241. if (!this._cachedVertexArrayObject) {
  9242. return;
  9243. }
  9244. this._cachedVertexArrayObject = null;
  9245. this._gl.bindVertexArray(null);
  9246. };
  9247. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9248. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9249. this._cachedVertexBuffers = vertexBuffers;
  9250. this._cachedEffectForVertexBuffers = effect;
  9251. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9252. }
  9253. this._bindIndexBufferWithCache(indexBuffer);
  9254. };
  9255. Engine.prototype.unbindInstanceAttributes = function () {
  9256. var boundBuffer;
  9257. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9258. var instancesBuffer = this._currentInstanceBuffers[i];
  9259. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9260. boundBuffer = instancesBuffer;
  9261. this.bindArrayBuffer(instancesBuffer);
  9262. }
  9263. var offsetLocation = this._currentInstanceLocations[i];
  9264. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9265. }
  9266. this._currentInstanceBuffers.length = 0;
  9267. this._currentInstanceLocations.length = 0;
  9268. };
  9269. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9270. this._gl.deleteVertexArray(vao);
  9271. };
  9272. Engine.prototype._releaseBuffer = function (buffer) {
  9273. buffer.references--;
  9274. if (buffer.references === 0) {
  9275. this._gl.deleteBuffer(buffer);
  9276. return true;
  9277. }
  9278. return false;
  9279. };
  9280. Engine.prototype.createInstancesBuffer = function (capacity) {
  9281. var buffer = this._gl.createBuffer();
  9282. buffer.capacity = capacity;
  9283. this.bindArrayBuffer(buffer);
  9284. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9285. return buffer;
  9286. };
  9287. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9288. this._gl.deleteBuffer(buffer);
  9289. };
  9290. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9291. this.bindArrayBuffer(instancesBuffer);
  9292. if (data) {
  9293. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9294. }
  9295. if (offsetLocations[0].index !== undefined) {
  9296. var stride = 0;
  9297. for (var i = 0; i < offsetLocations.length; i++) {
  9298. var ai = offsetLocations[i];
  9299. stride += ai.attributeSize * 4;
  9300. }
  9301. for (var i = 0; i < offsetLocations.length; i++) {
  9302. var ai = offsetLocations[i];
  9303. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9304. this._gl.enableVertexAttribArray(ai.index);
  9305. this._vertexAttribArraysEnabled[ai.index] = true;
  9306. }
  9307. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9308. this._gl.vertexAttribDivisor(ai.index, 1);
  9309. this._currentInstanceLocations.push(ai.index);
  9310. this._currentInstanceBuffers.push(instancesBuffer);
  9311. }
  9312. }
  9313. else {
  9314. for (var index = 0; index < 4; index++) {
  9315. var offsetLocation = offsetLocations[index];
  9316. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9317. this._gl.enableVertexAttribArray(offsetLocation);
  9318. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9319. }
  9320. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9321. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9322. this._currentInstanceLocations.push(offsetLocation);
  9323. this._currentInstanceBuffers.push(instancesBuffer);
  9324. }
  9325. }
  9326. };
  9327. Engine.prototype.applyStates = function () {
  9328. this._depthCullingState.apply(this._gl);
  9329. this._stencilState.apply(this._gl);
  9330. this._alphaState.apply(this._gl);
  9331. };
  9332. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9333. // Apply states
  9334. this.applyStates();
  9335. this._drawCalls.addCount(1, false);
  9336. // Render
  9337. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9338. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9339. if (instancesCount) {
  9340. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9341. return;
  9342. }
  9343. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9344. };
  9345. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9346. // Apply states
  9347. this.applyStates();
  9348. this._drawCalls.addCount(1, false);
  9349. if (instancesCount) {
  9350. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9351. return;
  9352. }
  9353. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9354. };
  9355. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9356. // Apply states
  9357. this.applyStates();
  9358. this._drawCalls.addCount(1, false);
  9359. if (instancesCount) {
  9360. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9361. return;
  9362. }
  9363. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9364. };
  9365. // Shaders
  9366. Engine.prototype._releaseEffect = function (effect) {
  9367. if (this._compiledEffects[effect._key]) {
  9368. delete this._compiledEffects[effect._key];
  9369. if (effect.getProgram()) {
  9370. this._gl.deleteProgram(effect.getProgram());
  9371. }
  9372. }
  9373. };
  9374. /**
  9375. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9376. * @param samplers An array of string used to represent textures
  9377. */
  9378. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9379. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9380. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9381. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9382. if (this._compiledEffects[name]) {
  9383. var compiledEffect = this._compiledEffects[name];
  9384. if (onCompiled && compiledEffect.isReady()) {
  9385. onCompiled(compiledEffect);
  9386. }
  9387. return compiledEffect;
  9388. }
  9389. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9390. effect._key = name;
  9391. this._compiledEffects[name] = effect;
  9392. return effect;
  9393. };
  9394. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9395. if (uniformsNames === void 0) { uniformsNames = []; }
  9396. if (samplers === void 0) { samplers = []; }
  9397. if (defines === void 0) { defines = ""; }
  9398. return this.createEffect({
  9399. vertex: "particles",
  9400. fragmentElement: fragmentName
  9401. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9402. };
  9403. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9404. context = context || this._gl;
  9405. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9406. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9407. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9408. var shaderProgram = context.createProgram();
  9409. context.attachShader(shaderProgram, vertexShader);
  9410. context.attachShader(shaderProgram, fragmentShader);
  9411. context.linkProgram(shaderProgram);
  9412. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9413. if (!linked) {
  9414. context.validateProgram(shaderProgram);
  9415. var error = context.getProgramInfoLog(shaderProgram);
  9416. if (error) {
  9417. throw new Error(error);
  9418. }
  9419. }
  9420. context.deleteShader(vertexShader);
  9421. context.deleteShader(fragmentShader);
  9422. return shaderProgram;
  9423. };
  9424. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9425. var results = [];
  9426. for (var index = 0; index < uniformsNames.length; index++) {
  9427. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9428. }
  9429. return results;
  9430. };
  9431. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9432. var results = [];
  9433. for (var index = 0; index < attributesNames.length; index++) {
  9434. try {
  9435. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9436. }
  9437. catch (e) {
  9438. results.push(-1);
  9439. }
  9440. }
  9441. return results;
  9442. };
  9443. Engine.prototype.enableEffect = function (effect) {
  9444. // Use program
  9445. this.setProgram(effect.getProgram());
  9446. this._currentEffect = effect;
  9447. if (effect.onBind) {
  9448. effect.onBind(effect);
  9449. }
  9450. effect.onBindObservable.notifyObservers(effect);
  9451. };
  9452. Engine.prototype.setIntArray = function (uniform, array) {
  9453. if (!uniform)
  9454. return;
  9455. this._gl.uniform1iv(uniform, array);
  9456. };
  9457. Engine.prototype.setIntArray2 = function (uniform, array) {
  9458. if (!uniform || array.length % 2 !== 0)
  9459. return;
  9460. this._gl.uniform2iv(uniform, array);
  9461. };
  9462. Engine.prototype.setIntArray3 = function (uniform, array) {
  9463. if (!uniform || array.length % 3 !== 0)
  9464. return;
  9465. this._gl.uniform3iv(uniform, array);
  9466. };
  9467. Engine.prototype.setIntArray4 = function (uniform, array) {
  9468. if (!uniform || array.length % 4 !== 0)
  9469. return;
  9470. this._gl.uniform4iv(uniform, array);
  9471. };
  9472. Engine.prototype.setFloatArray = function (uniform, array) {
  9473. if (!uniform)
  9474. return;
  9475. this._gl.uniform1fv(uniform, array);
  9476. };
  9477. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9478. if (!uniform || array.length % 2 !== 0)
  9479. return;
  9480. this._gl.uniform2fv(uniform, array);
  9481. };
  9482. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9483. if (!uniform || array.length % 3 !== 0)
  9484. return;
  9485. this._gl.uniform3fv(uniform, array);
  9486. };
  9487. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9488. if (!uniform || array.length % 4 !== 0)
  9489. return;
  9490. this._gl.uniform4fv(uniform, array);
  9491. };
  9492. Engine.prototype.setArray = function (uniform, array) {
  9493. if (!uniform)
  9494. return;
  9495. this._gl.uniform1fv(uniform, array);
  9496. };
  9497. Engine.prototype.setArray2 = function (uniform, array) {
  9498. if (!uniform || array.length % 2 !== 0)
  9499. return;
  9500. this._gl.uniform2fv(uniform, array);
  9501. };
  9502. Engine.prototype.setArray3 = function (uniform, array) {
  9503. if (!uniform || array.length % 3 !== 0)
  9504. return;
  9505. this._gl.uniform3fv(uniform, array);
  9506. };
  9507. Engine.prototype.setArray4 = function (uniform, array) {
  9508. if (!uniform || array.length % 4 !== 0)
  9509. return;
  9510. this._gl.uniform4fv(uniform, array);
  9511. };
  9512. Engine.prototype.setMatrices = function (uniform, matrices) {
  9513. if (!uniform)
  9514. return;
  9515. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9516. };
  9517. Engine.prototype.setMatrix = function (uniform, matrix) {
  9518. if (!uniform)
  9519. return;
  9520. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9521. };
  9522. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9523. if (!uniform)
  9524. return;
  9525. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9526. };
  9527. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9528. if (!uniform)
  9529. return;
  9530. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9531. };
  9532. Engine.prototype.setFloat = function (uniform, value) {
  9533. if (!uniform)
  9534. return;
  9535. this._gl.uniform1f(uniform, value);
  9536. };
  9537. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9538. if (!uniform)
  9539. return;
  9540. this._gl.uniform2f(uniform, x, y);
  9541. };
  9542. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9543. if (!uniform)
  9544. return;
  9545. this._gl.uniform3f(uniform, x, y, z);
  9546. };
  9547. Engine.prototype.setBool = function (uniform, bool) {
  9548. if (!uniform)
  9549. return;
  9550. this._gl.uniform1i(uniform, bool);
  9551. };
  9552. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9553. if (!uniform)
  9554. return;
  9555. this._gl.uniform4f(uniform, x, y, z, w);
  9556. };
  9557. Engine.prototype.setColor3 = function (uniform, color3) {
  9558. if (!uniform)
  9559. return;
  9560. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9561. };
  9562. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9563. if (!uniform)
  9564. return;
  9565. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9566. };
  9567. // States
  9568. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9569. if (zOffset === void 0) { zOffset = 0; }
  9570. if (reverseSide === void 0) { reverseSide = false; }
  9571. // Culling
  9572. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9573. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9574. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9575. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9576. if (culling) {
  9577. this._depthCullingState.cullFace = cullFace;
  9578. this._depthCullingState.cull = true;
  9579. }
  9580. else {
  9581. this._depthCullingState.cull = false;
  9582. }
  9583. }
  9584. // Z offset
  9585. this.setZOffset(zOffset);
  9586. };
  9587. Engine.prototype.setZOffset = function (value) {
  9588. this._depthCullingState.zOffset = value;
  9589. };
  9590. Engine.prototype.getZOffset = function () {
  9591. return this._depthCullingState.zOffset;
  9592. };
  9593. Engine.prototype.setDepthBuffer = function (enable) {
  9594. this._depthCullingState.depthTest = enable;
  9595. };
  9596. Engine.prototype.getDepthWrite = function () {
  9597. return this._depthCullingState.depthMask;
  9598. };
  9599. Engine.prototype.setDepthWrite = function (enable) {
  9600. this._depthCullingState.depthMask = enable;
  9601. };
  9602. Engine.prototype.setColorWrite = function (enable) {
  9603. this._gl.colorMask(enable, enable, enable, enable);
  9604. this._colorWrite = enable;
  9605. };
  9606. Engine.prototype.getColorWrite = function () {
  9607. return this._colorWrite;
  9608. };
  9609. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9610. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9611. };
  9612. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9613. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9614. if (this._alphaMode === mode) {
  9615. return;
  9616. }
  9617. switch (mode) {
  9618. case Engine.ALPHA_DISABLE:
  9619. this._alphaState.alphaBlend = false;
  9620. break;
  9621. case Engine.ALPHA_PREMULTIPLIED:
  9622. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9623. this._alphaState.alphaBlend = true;
  9624. break;
  9625. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9626. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9627. this._alphaState.alphaBlend = true;
  9628. break;
  9629. case Engine.ALPHA_COMBINE:
  9630. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9631. this._alphaState.alphaBlend = true;
  9632. break;
  9633. case Engine.ALPHA_ONEONE:
  9634. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9635. this._alphaState.alphaBlend = true;
  9636. break;
  9637. case Engine.ALPHA_ADD:
  9638. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9639. this._alphaState.alphaBlend = true;
  9640. break;
  9641. case Engine.ALPHA_SUBTRACT:
  9642. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9643. this._alphaState.alphaBlend = true;
  9644. break;
  9645. case Engine.ALPHA_MULTIPLY:
  9646. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9647. this._alphaState.alphaBlend = true;
  9648. break;
  9649. case Engine.ALPHA_MAXIMIZED:
  9650. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9651. this._alphaState.alphaBlend = true;
  9652. break;
  9653. case Engine.ALPHA_INTERPOLATE:
  9654. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9655. this._alphaState.alphaBlend = true;
  9656. break;
  9657. case Engine.ALPHA_SCREENMODE:
  9658. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9659. this._alphaState.alphaBlend = true;
  9660. break;
  9661. }
  9662. if (!noDepthWriteChange) {
  9663. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9664. }
  9665. this._alphaMode = mode;
  9666. };
  9667. Engine.prototype.getAlphaMode = function () {
  9668. return this._alphaMode;
  9669. };
  9670. Engine.prototype.setAlphaTesting = function (enable) {
  9671. this._alphaTest = enable;
  9672. };
  9673. Engine.prototype.getAlphaTesting = function () {
  9674. return !!this._alphaTest;
  9675. };
  9676. // Textures
  9677. Engine.prototype.wipeCaches = function (bruteForce) {
  9678. if (this.preventCacheWipeBetweenFrames) {
  9679. return;
  9680. }
  9681. this.resetTextureCache();
  9682. this._currentEffect = null;
  9683. // 6/8/2017: deltakosh: Should not be required anymore.
  9684. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9685. if (bruteForce) {
  9686. this._currentProgram = null;
  9687. this._stencilState.reset();
  9688. this._depthCullingState.reset();
  9689. this.setDepthFunctionToLessOrEqual();
  9690. this._alphaState.reset();
  9691. }
  9692. this._cachedVertexBuffers = null;
  9693. this._cachedIndexBuffer = null;
  9694. this._cachedEffectForVertexBuffers = null;
  9695. this._unbindVertexArrayObject();
  9696. this.bindIndexBuffer(null);
  9697. this.bindArrayBuffer(null);
  9698. };
  9699. /**
  9700. * Set the compressed texture format to use, based on the formats you have, and the formats
  9701. * supported by the hardware / browser.
  9702. *
  9703. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9704. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9705. * to API arguments needed to compressed textures. This puts the burden on the container
  9706. * generator to house the arcane code for determining these for current & future formats.
  9707. *
  9708. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9709. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9710. *
  9711. * Note: The result of this call is not taken into account when a texture is base64.
  9712. *
  9713. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9714. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9715. *
  9716. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9717. * @returns The extension selected.
  9718. */
  9719. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9720. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9721. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9722. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9723. return this._textureFormatInUse = this._texturesSupported[i];
  9724. }
  9725. }
  9726. }
  9727. // actively set format to nothing, to allow this to be called more than once
  9728. // and possibly fail the 2nd time
  9729. return this._textureFormatInUse = null;
  9730. };
  9731. Engine.prototype._createTexture = function () {
  9732. return this._gl.createTexture();
  9733. };
  9734. /**
  9735. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9736. * @param {string} urlArg- This contains one of the following:
  9737. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9738. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9739. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9740. *
  9741. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9742. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9743. * @param {Scene} scene- Needed for loading to the correct scene.
  9744. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9745. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9746. * @param {callback} onError- Optional callback to be called upon failure.
  9747. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9748. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9749. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9750. *
  9751. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9752. */
  9753. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9754. var _this = this;
  9755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9756. if (onLoad === void 0) { onLoad = null; }
  9757. if (onError === void 0) { onError = null; }
  9758. if (buffer === void 0) { buffer = null; }
  9759. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9760. var fromData = url.substr(0, 5) === "data:";
  9761. var fromBlob = url.substr(0, 5) === "blob:";
  9762. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9763. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9764. // establish the file extension, if possible
  9765. var lastDot = url.lastIndexOf('.');
  9766. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9767. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9768. var isTGA = (extension === ".tga");
  9769. // determine if a ktx file should be substituted
  9770. var isKTX = false;
  9771. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9772. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9773. isKTX = true;
  9774. }
  9775. if (scene) {
  9776. scene._addPendingData(texture);
  9777. }
  9778. texture.url = url;
  9779. texture.generateMipMaps = !noMipmap;
  9780. texture.samplingMode = samplingMode;
  9781. texture.invertY = invertY;
  9782. if (!this._doNotHandleContextLost) {
  9783. // Keep a link to the buffer only if we plan to handle context lost
  9784. texture._buffer = buffer;
  9785. }
  9786. if (onLoad) {
  9787. texture.onLoadedObservable.add(onLoad);
  9788. }
  9789. if (!fallBack)
  9790. this._internalTexturesCache.push(texture);
  9791. var onerror = function () {
  9792. if (scene) {
  9793. scene._removePendingData(texture);
  9794. }
  9795. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9796. if (isKTX) {
  9797. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9798. }
  9799. else if (onError) {
  9800. onError();
  9801. }
  9802. };
  9803. var callback;
  9804. // processing for non-image formats
  9805. if (isKTX || isTGA || isDDS) {
  9806. if (isKTX) {
  9807. callback = function (data) {
  9808. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9809. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9810. ktx.uploadLevels(_this._gl, !noMipmap);
  9811. return false;
  9812. }, samplingMode);
  9813. };
  9814. }
  9815. else if (isTGA) {
  9816. callback = function (arrayBuffer) {
  9817. var data = new Uint8Array(arrayBuffer);
  9818. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9819. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9820. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9821. return false;
  9822. }, samplingMode);
  9823. };
  9824. }
  9825. else if (isDDS) {
  9826. callback = function (data) {
  9827. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9828. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9829. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9830. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9831. return false;
  9832. }, samplingMode);
  9833. };
  9834. }
  9835. if (!buffer) {
  9836. BABYLON.Tools.LoadFile(url, function (data) {
  9837. callback(data);
  9838. }, null, scene ? scene.database : null, true, onerror);
  9839. }
  9840. else {
  9841. callback(buffer);
  9842. }
  9843. // image format processing
  9844. }
  9845. else {
  9846. var onload = function (img) {
  9847. if (fromBlob && !_this._doNotHandleContextLost) {
  9848. // We need to store the image if we need to rebuild the texture
  9849. // in case of a webgl context lost
  9850. texture._buffer = img;
  9851. }
  9852. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9853. var gl = _this._gl;
  9854. var isPot = (img.width === potWidth && img.height === potHeight);
  9855. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9856. if (isPot) {
  9857. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9858. return false;
  9859. }
  9860. // Using shaders to rescale because canvas.drawImage is lossy
  9861. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9862. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9863. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9864. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9868. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9869. _this._releaseTexture(source);
  9870. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9871. continuationCallback();
  9872. });
  9873. return true;
  9874. }, samplingMode);
  9875. };
  9876. if (!fromData || isBase64)
  9877. if (buffer instanceof HTMLImageElement) {
  9878. onload(buffer);
  9879. }
  9880. else {
  9881. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9882. }
  9883. else if (buffer instanceof Array || typeof buffer === "string")
  9884. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9885. else
  9886. onload(buffer);
  9887. }
  9888. return texture;
  9889. };
  9890. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9891. var _this = this;
  9892. var rtt = this.createRenderTargetTexture({
  9893. width: destination.width,
  9894. height: destination.height,
  9895. }, {
  9896. generateMipMaps: false,
  9897. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9898. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9899. generateDepthBuffer: false,
  9900. generateStencilBuffer: false
  9901. });
  9902. if (!this._rescalePostProcess) {
  9903. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9904. }
  9905. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9906. _this._rescalePostProcess.onApply = function (effect) {
  9907. effect._bindTexture("textureSampler", source);
  9908. };
  9909. var hostingScene = scene;
  9910. if (!hostingScene) {
  9911. hostingScene = _this.scenes[_this.scenes.length - 1];
  9912. }
  9913. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9914. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9915. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9916. _this.unBindFramebuffer(rtt);
  9917. _this._releaseTexture(rtt);
  9918. if (onComplete) {
  9919. onComplete();
  9920. }
  9921. });
  9922. };
  9923. Engine.prototype._getInternalFormat = function (format) {
  9924. var internalFormat = this._gl.RGBA;
  9925. switch (format) {
  9926. case Engine.TEXTUREFORMAT_ALPHA:
  9927. internalFormat = this._gl.ALPHA;
  9928. break;
  9929. case Engine.TEXTUREFORMAT_LUMINANCE:
  9930. internalFormat = this._gl.LUMINANCE;
  9931. break;
  9932. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9933. internalFormat = this._gl.LUMINANCE_ALPHA;
  9934. break;
  9935. case Engine.TEXTUREFORMAT_RGB:
  9936. internalFormat = this._gl.RGB;
  9937. break;
  9938. case Engine.TEXTUREFORMAT_RGBA:
  9939. internalFormat = this._gl.RGBA;
  9940. break;
  9941. }
  9942. return internalFormat;
  9943. };
  9944. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9945. if (compression === void 0) { compression = null; }
  9946. var internalFormat = this._getInternalFormat(format);
  9947. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9948. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9949. if (!this._doNotHandleContextLost) {
  9950. texture._bufferView = data;
  9951. texture.format = format;
  9952. texture.invertY = invertY;
  9953. texture._compression = compression;
  9954. }
  9955. if (texture.width % 4 !== 0) {
  9956. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9957. }
  9958. if (compression) {
  9959. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9960. }
  9961. else {
  9962. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9963. }
  9964. if (texture.generateMipMaps) {
  9965. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9966. }
  9967. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9968. this.resetTextureCache();
  9969. texture.isReady = true;
  9970. };
  9971. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9972. if (compression === void 0) { compression = null; }
  9973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9974. texture.baseWidth = width;
  9975. texture.baseHeight = height;
  9976. texture.width = width;
  9977. texture.height = height;
  9978. texture.format = format;
  9979. texture.generateMipMaps = generateMipMaps;
  9980. texture.samplingMode = samplingMode;
  9981. texture.invertY = invertY;
  9982. texture._compression = compression;
  9983. if (!this._doNotHandleContextLost) {
  9984. texture._bufferView = data;
  9985. }
  9986. this.updateRawTexture(texture, data, format, invertY, compression);
  9987. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9988. // Filters
  9989. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9990. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9991. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9992. if (generateMipMaps) {
  9993. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9994. }
  9995. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9996. this._internalTexturesCache.push(texture);
  9997. return texture;
  9998. };
  9999. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10000. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10001. texture.baseWidth = width;
  10002. texture.baseHeight = height;
  10003. if (generateMipMaps) {
  10004. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10005. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10006. }
  10007. this.resetTextureCache();
  10008. texture.width = width;
  10009. texture.height = height;
  10010. texture.isReady = false;
  10011. texture.generateMipMaps = generateMipMaps;
  10012. texture.samplingMode = samplingMode;
  10013. this.updateTextureSamplingMode(samplingMode, texture);
  10014. this._internalTexturesCache.push(texture);
  10015. return texture;
  10016. };
  10017. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10018. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10019. if (texture.isCube) {
  10020. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10021. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10022. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10023. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10024. }
  10025. else {
  10026. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10027. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10029. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10030. }
  10031. texture.samplingMode = samplingMode;
  10032. };
  10033. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10034. if (premulAlpha === void 0) { premulAlpha = false; }
  10035. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10036. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10037. if (premulAlpha) {
  10038. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10039. }
  10040. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10041. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10042. if (texture.generateMipMaps) {
  10043. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10044. }
  10045. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10046. if (premulAlpha) {
  10047. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10048. }
  10049. this.resetTextureCache();
  10050. texture.isReady = true;
  10051. };
  10052. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10053. if (texture._isDisabled) {
  10054. return;
  10055. }
  10056. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10057. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10058. try {
  10059. // Testing video texture support
  10060. if (this._videoTextureSupported === undefined) {
  10061. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10062. if (this._gl.getError() !== 0) {
  10063. this._videoTextureSupported = false;
  10064. }
  10065. else {
  10066. this._videoTextureSupported = true;
  10067. }
  10068. }
  10069. // Copy video through the current working canvas if video texture is not supported
  10070. if (!this._videoTextureSupported) {
  10071. if (!texture._workingCanvas) {
  10072. texture._workingCanvas = document.createElement("canvas");
  10073. texture._workingContext = texture._workingCanvas.getContext("2d");
  10074. texture._workingCanvas.width = texture.width;
  10075. texture._workingCanvas.height = texture.height;
  10076. }
  10077. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10078. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10079. }
  10080. else {
  10081. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10082. }
  10083. if (texture.generateMipMaps) {
  10084. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10085. }
  10086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10087. this.resetTextureCache();
  10088. texture.isReady = true;
  10089. }
  10090. catch (ex) {
  10091. // Something unexpected
  10092. // Let's disable the texture
  10093. texture._isDisabled = true;
  10094. }
  10095. };
  10096. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10097. var fullOptions = new RenderTargetCreationOptions();
  10098. if (options !== undefined && typeof options === "object") {
  10099. fullOptions.generateMipMaps = options.generateMipMaps;
  10100. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10101. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10102. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10103. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10104. }
  10105. else {
  10106. fullOptions.generateMipMaps = options;
  10107. fullOptions.generateDepthBuffer = true;
  10108. fullOptions.generateStencilBuffer = false;
  10109. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10110. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10111. }
  10112. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10113. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10114. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10115. }
  10116. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10117. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10118. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10119. }
  10120. var gl = this._gl;
  10121. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10122. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10123. var width = size.width || size;
  10124. var height = size.height || size;
  10125. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10126. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10127. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10128. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10129. }
  10130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10132. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10134. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10135. // Create the framebuffer
  10136. var framebuffer = gl.createFramebuffer();
  10137. this.bindUnboundFramebuffer(framebuffer);
  10138. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10139. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10140. if (fullOptions.generateMipMaps) {
  10141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10142. }
  10143. // Unbind
  10144. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10145. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10146. this.bindUnboundFramebuffer(null);
  10147. texture._framebuffer = framebuffer;
  10148. texture.baseWidth = width;
  10149. texture.baseHeight = height;
  10150. texture.width = width;
  10151. texture.height = height;
  10152. texture.isReady = true;
  10153. texture.samples = 1;
  10154. texture.generateMipMaps = fullOptions.generateMipMaps;
  10155. texture.samplingMode = fullOptions.samplingMode;
  10156. texture.type = fullOptions.type;
  10157. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10158. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10159. this.resetTextureCache();
  10160. this._internalTexturesCache.push(texture);
  10161. return texture;
  10162. };
  10163. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10164. var generateMipMaps = false;
  10165. var generateDepthBuffer = true;
  10166. var generateStencilBuffer = false;
  10167. var generateDepthTexture = false;
  10168. var textureCount = 1;
  10169. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10170. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10171. var types = [], samplingModes = [];
  10172. if (options !== undefined) {
  10173. generateMipMaps = options.generateMipMaps;
  10174. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10175. generateStencilBuffer = options.generateStencilBuffer;
  10176. generateDepthTexture = options.generateDepthTexture;
  10177. textureCount = options.textureCount || 1;
  10178. if (options.types) {
  10179. types = options.types;
  10180. }
  10181. if (options.samplingModes) {
  10182. samplingModes = options.samplingModes;
  10183. }
  10184. }
  10185. var gl = this._gl;
  10186. // Create the framebuffer
  10187. var framebuffer = gl.createFramebuffer();
  10188. this.bindUnboundFramebuffer(framebuffer);
  10189. var width = size.width || size;
  10190. var height = size.height || size;
  10191. var textures = [];
  10192. var attachments = [];
  10193. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10194. for (var i = 0; i < textureCount; i++) {
  10195. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10196. var type = types[i] || defaultType;
  10197. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10198. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10199. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10200. }
  10201. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10202. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10203. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10204. }
  10205. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10206. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10207. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10208. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10209. }
  10210. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10211. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10212. textures.push(texture);
  10213. attachments.push(attachment);
  10214. gl.activeTexture(gl["TEXTURE" + i]);
  10215. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10220. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10221. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10222. if (generateMipMaps) {
  10223. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10224. }
  10225. // Unbind
  10226. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10227. texture._framebuffer = framebuffer;
  10228. texture._depthStencilBuffer = depthStencilBuffer;
  10229. texture.baseWidth = width;
  10230. texture.baseHeight = height;
  10231. texture.width = width;
  10232. texture.height = height;
  10233. texture.isReady = true;
  10234. texture.samples = 1;
  10235. texture.generateMipMaps = generateMipMaps;
  10236. texture.samplingMode = samplingMode;
  10237. texture.type = type;
  10238. texture._generateDepthBuffer = generateDepthBuffer;
  10239. texture._generateStencilBuffer = generateStencilBuffer;
  10240. this._internalTexturesCache.push(texture);
  10241. }
  10242. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10243. // Depth texture
  10244. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10245. gl.activeTexture(gl.TEXTURE0);
  10246. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10251. 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);
  10252. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10253. depthTexture._framebuffer = framebuffer;
  10254. depthTexture.baseWidth = width;
  10255. depthTexture.baseHeight = height;
  10256. depthTexture.width = width;
  10257. depthTexture.height = height;
  10258. depthTexture.isReady = true;
  10259. depthTexture.samples = 1;
  10260. depthTexture.generateMipMaps = generateMipMaps;
  10261. depthTexture.samplingMode = gl.NEAREST;
  10262. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10263. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10264. textures.push(depthTexture);
  10265. this._internalTexturesCache.push(depthTexture);
  10266. }
  10267. gl.drawBuffers(attachments);
  10268. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10269. this.bindUnboundFramebuffer(null);
  10270. this.resetTextureCache();
  10271. return textures;
  10272. };
  10273. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10274. if (samples === void 0) { samples = 1; }
  10275. var depthStencilBuffer = null;
  10276. var gl = this._gl;
  10277. // Create the depth/stencil buffer
  10278. if (generateStencilBuffer) {
  10279. depthStencilBuffer = gl.createRenderbuffer();
  10280. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10281. if (samples > 1) {
  10282. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10283. }
  10284. else {
  10285. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10286. }
  10287. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10288. }
  10289. else if (generateDepthBuffer) {
  10290. depthStencilBuffer = gl.createRenderbuffer();
  10291. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10292. if (samples > 1) {
  10293. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10294. }
  10295. else {
  10296. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10297. }
  10298. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10299. }
  10300. return depthStencilBuffer;
  10301. };
  10302. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10303. if (this.webGLVersion < 2) {
  10304. return 1;
  10305. }
  10306. if (texture.samples === samples) {
  10307. return samples;
  10308. }
  10309. var gl = this._gl;
  10310. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10311. // Dispose previous render buffers
  10312. if (texture._depthStencilBuffer) {
  10313. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10314. }
  10315. if (texture._MSAAFramebuffer) {
  10316. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10317. }
  10318. if (texture._MSAARenderBuffer) {
  10319. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10320. }
  10321. if (samples > 1) {
  10322. texture._MSAAFramebuffer = gl.createFramebuffer();
  10323. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10324. var colorRenderbuffer = gl.createRenderbuffer();
  10325. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10326. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10327. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10328. texture._MSAARenderBuffer = colorRenderbuffer;
  10329. }
  10330. else {
  10331. this.bindUnboundFramebuffer(texture._framebuffer);
  10332. }
  10333. texture.samples = samples;
  10334. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10335. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10336. this.bindUnboundFramebuffer(null);
  10337. return samples;
  10338. };
  10339. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10340. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10341. };
  10342. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10343. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10344. };
  10345. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10346. var gl = this._gl;
  10347. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10348. var generateMipMaps = true;
  10349. var generateDepthBuffer = true;
  10350. var generateStencilBuffer = false;
  10351. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10352. if (options !== undefined) {
  10353. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10354. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10355. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10356. if (options.samplingMode !== undefined) {
  10357. samplingMode = options.samplingMode;
  10358. }
  10359. }
  10360. texture.isCube = true;
  10361. texture.generateMipMaps = generateMipMaps;
  10362. texture.samples = 1;
  10363. texture.samplingMode = samplingMode;
  10364. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10365. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10366. for (var face = 0; face < 6; face++) {
  10367. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10368. }
  10369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10373. // Create the framebuffer
  10374. var framebuffer = gl.createFramebuffer();
  10375. this.bindUnboundFramebuffer(framebuffer);
  10376. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10377. // Mipmaps
  10378. if (texture.generateMipMaps) {
  10379. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10380. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10381. }
  10382. // Unbind
  10383. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10384. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10385. this.bindUnboundFramebuffer(null);
  10386. texture._framebuffer = framebuffer;
  10387. texture.width = size;
  10388. texture.height = size;
  10389. texture.isReady = true;
  10390. this.resetTextureCache();
  10391. this._internalTexturesCache.push(texture);
  10392. return texture;
  10393. };
  10394. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10395. var _this = this;
  10396. if (onError === void 0) { onError = null; }
  10397. if (forcedExtension === void 0) { forcedExtension = null; }
  10398. var callback = function (loadData) {
  10399. if (!loadData) {
  10400. if (onLoad) {
  10401. onLoad(null);
  10402. }
  10403. return;
  10404. }
  10405. var texture = loadData.texture;
  10406. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10407. texture._lodGenerationScale = scale;
  10408. texture._lodGenerationOffset = offset;
  10409. if (_this._caps.textureLOD) {
  10410. // Do not add extra process if texture lod is supported.
  10411. if (onLoad) {
  10412. onLoad(texture);
  10413. }
  10414. return;
  10415. }
  10416. var mipSlices = 3;
  10417. var gl = _this._gl;
  10418. var width = loadData.width;
  10419. if (!width) {
  10420. return;
  10421. }
  10422. var textures = [];
  10423. for (var i = 0; i < mipSlices; i++) {
  10424. //compute LOD from even spacing in smoothness (matching shader calculation)
  10425. var smoothness = i / (mipSlices - 1);
  10426. var roughness = 1 - smoothness;
  10427. var minLODIndex = offset; // roughness = 0
  10428. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10429. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10430. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10431. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10432. glTextureFromLod.isCube = true;
  10433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10438. if (loadData.isDDS) {
  10439. var info = loadData.info;
  10440. var data = loadData.data;
  10441. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10442. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10443. }
  10444. else {
  10445. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10446. }
  10447. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10448. // Wrap in a base texture for easy binding.
  10449. var lodTexture = new BABYLON.BaseTexture(scene);
  10450. lodTexture.isCube = true;
  10451. lodTexture._texture = glTextureFromLod;
  10452. glTextureFromLod.isReady = true;
  10453. textures.push(lodTexture);
  10454. }
  10455. texture._lodTextureHigh = textures[2];
  10456. texture._lodTextureMid = textures[1];
  10457. texture._lodTextureLow = textures[0];
  10458. if (onLoad) {
  10459. onLoad(texture);
  10460. }
  10461. };
  10462. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10463. };
  10464. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10465. var _this = this;
  10466. if (onLoad === void 0) { onLoad = null; }
  10467. if (onError === void 0) { onError = null; }
  10468. if (forcedExtension === void 0) { forcedExtension = null; }
  10469. var gl = this._gl;
  10470. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10471. texture.isCube = true;
  10472. texture.url = rootUrl;
  10473. texture.generateMipMaps = !noMipmap;
  10474. if (!this._doNotHandleContextLost) {
  10475. texture._extension = forcedExtension;
  10476. texture._files = files;
  10477. }
  10478. var isKTX = false;
  10479. var isDDS = false;
  10480. var lastDot = rootUrl.lastIndexOf('.');
  10481. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10482. if (this._textureFormatInUse) {
  10483. extension = this._textureFormatInUse;
  10484. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10485. isKTX = true;
  10486. }
  10487. else {
  10488. isDDS = (extension === ".dds");
  10489. }
  10490. if (isKTX) {
  10491. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10492. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10493. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10494. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10495. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10496. ktx.uploadLevels(_this._gl, !noMipmap);
  10497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10501. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10502. _this.resetTextureCache();
  10503. texture.width = ktx.pixelWidth;
  10504. texture.height = ktx.pixelHeight;
  10505. texture.isReady = true;
  10506. }, null, null, true, onError);
  10507. }
  10508. else if (isDDS) {
  10509. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10510. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10511. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10512. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10513. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10514. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10515. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10516. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10517. }
  10518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10522. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10523. _this.resetTextureCache();
  10524. texture.width = info.width;
  10525. texture.height = info.height;
  10526. texture.isReady = true;
  10527. texture.type = info.textureType;
  10528. if (onLoad) {
  10529. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10530. }
  10531. }, null, null, true, onError);
  10532. }
  10533. else {
  10534. cascadeLoad(rootUrl, scene, function (imgs) {
  10535. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10536. var height = width;
  10537. _this._prepareWorkingCanvas();
  10538. _this._workingCanvas.width = width;
  10539. _this._workingCanvas.height = height;
  10540. var faces = [
  10541. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10542. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10543. ];
  10544. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10545. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10546. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10547. for (var index = 0; index < faces.length; index++) {
  10548. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10549. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10550. }
  10551. if (!noMipmap) {
  10552. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10553. }
  10554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10558. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10559. _this.resetTextureCache();
  10560. texture.width = width;
  10561. texture.height = height;
  10562. texture.isReady = true;
  10563. texture.format = format;
  10564. texture.onLoadedObservable.notifyObservers(texture);
  10565. texture.onLoadedObservable.clear();
  10566. if (onLoad) {
  10567. onLoad();
  10568. }
  10569. }, files, onError);
  10570. }
  10571. this._internalTexturesCache.push(texture);
  10572. return texture;
  10573. };
  10574. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10575. if (compression === void 0) { compression = null; }
  10576. if (level === void 0) { level = 0; }
  10577. texture._bufferViewArray = data;
  10578. texture.format = format;
  10579. texture.type = type;
  10580. texture.invertY = invertY;
  10581. texture._compression = compression;
  10582. var gl = this._gl;
  10583. var textureType = this._getWebGLTextureType(type);
  10584. var internalFormat = this._getInternalFormat(format);
  10585. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10586. var needConversion = false;
  10587. if (internalFormat === gl.RGB) {
  10588. internalFormat = gl.RGBA;
  10589. needConversion = true;
  10590. }
  10591. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10592. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10593. if (texture.width % 4 !== 0) {
  10594. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10595. }
  10596. // Data are known to be in +X +Y +Z -X -Y -Z
  10597. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10598. var faceData = data[faceIndex];
  10599. if (compression) {
  10600. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10601. }
  10602. else {
  10603. if (needConversion) {
  10604. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10605. }
  10606. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10607. }
  10608. }
  10609. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10610. if (isPot && texture.generateMipMaps && level === 0) {
  10611. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10612. }
  10613. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10614. this.resetTextureCache();
  10615. texture.isReady = true;
  10616. };
  10617. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10618. if (compression === void 0) { compression = null; }
  10619. var gl = this._gl;
  10620. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10621. texture.isCube = true;
  10622. texture.generateMipMaps = generateMipMaps;
  10623. texture.format = format;
  10624. texture.type = type;
  10625. if (!this._doNotHandleContextLost) {
  10626. texture._bufferViewArray = data;
  10627. }
  10628. var textureType = this._getWebGLTextureType(type);
  10629. var internalFormat = this._getInternalFormat(format);
  10630. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10631. var needConversion = false;
  10632. if (internalFormat === gl.RGB) {
  10633. internalFormat = gl.RGBA;
  10634. needConversion = true;
  10635. }
  10636. var width = size;
  10637. var height = width;
  10638. texture.width = width;
  10639. texture.height = height;
  10640. // Double check on POT to generate Mips.
  10641. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10642. if (!isPot) {
  10643. generateMipMaps = false;
  10644. }
  10645. // Upload data if needed. The texture won't be ready until then.
  10646. if (data) {
  10647. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10648. }
  10649. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10650. // Filters
  10651. if (data && generateMipMaps) {
  10652. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10653. }
  10654. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10657. }
  10658. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10661. }
  10662. else {
  10663. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10666. }
  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. return texture;
  10671. };
  10672. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10673. var _this = this;
  10674. if (onLoad === void 0) { onLoad = null; }
  10675. if (onError === void 0) { onError = null; }
  10676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10677. if (invertY === void 0) { invertY = false; }
  10678. var gl = this._gl;
  10679. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10680. scene._addPendingData(texture);
  10681. texture.url = url;
  10682. this._internalTexturesCache.push(texture);
  10683. var onerror = function () {
  10684. scene._removePendingData(texture);
  10685. if (onError) {
  10686. onError();
  10687. }
  10688. };
  10689. var internalCallback = function (data) {
  10690. var width = texture.width;
  10691. var height = texture.height;
  10692. var faceDataArrays = callback(data);
  10693. if (mipmmapGenerator) {
  10694. var textureType = _this._getWebGLTextureType(type);
  10695. var internalFormat = _this._getInternalFormat(format);
  10696. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10697. var needConversion = false;
  10698. if (internalFormat === gl.RGB) {
  10699. internalFormat = gl.RGBA;
  10700. needConversion = true;
  10701. }
  10702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10703. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10704. var mipData = mipmmapGenerator(faceDataArrays);
  10705. for (var level = 0; level < mipData.length; level++) {
  10706. var mipSize = width >> level;
  10707. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10708. var mipFaceData = mipData[level][faceIndex];
  10709. if (needConversion) {
  10710. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10711. }
  10712. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10713. }
  10714. }
  10715. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10716. }
  10717. else {
  10718. texture.generateMipMaps = !noMipmap;
  10719. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10720. }
  10721. texture.isReady = true;
  10722. _this.resetTextureCache();
  10723. scene._removePendingData(texture);
  10724. if (onLoad) {
  10725. onLoad();
  10726. }
  10727. };
  10728. BABYLON.Tools.LoadFile(url, function (data) {
  10729. internalCallback(data);
  10730. }, onerror, scene.database, true);
  10731. return texture;
  10732. };
  10733. ;
  10734. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10735. var gl = this._gl;
  10736. if (!gl) {
  10737. return;
  10738. }
  10739. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10742. if (!noMipmap && !isCompressed) {
  10743. gl.generateMipmap(gl.TEXTURE_2D);
  10744. }
  10745. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10746. this.resetTextureCache();
  10747. if (scene) {
  10748. scene._removePendingData(texture);
  10749. }
  10750. texture.onLoadedObservable.notifyObservers(texture);
  10751. texture.onLoadedObservable.clear();
  10752. };
  10753. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10754. var _this = this;
  10755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10756. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10757. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10758. var gl = this._gl;
  10759. if (!gl) {
  10760. return;
  10761. }
  10762. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10763. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10764. texture.baseWidth = width;
  10765. texture.baseHeight = height;
  10766. texture.width = potWidth;
  10767. texture.height = potHeight;
  10768. texture.isReady = true;
  10769. if (processFunction(potWidth, potHeight, function () {
  10770. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10771. })) {
  10772. // Returning as texture needs extra async steps
  10773. return;
  10774. }
  10775. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10776. };
  10777. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10778. // Create new RGBA data container.
  10779. var rgbaData;
  10780. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10781. rgbaData = new Float32Array(width * height * 4);
  10782. }
  10783. else {
  10784. rgbaData = new Uint32Array(width * height * 4);
  10785. }
  10786. // Convert each pixel.
  10787. for (var x = 0; x < width; x++) {
  10788. for (var y = 0; y < height; y++) {
  10789. var index = (y * width + x) * 3;
  10790. var newIndex = (y * width + x) * 4;
  10791. // Map Old Value to new value.
  10792. rgbaData[newIndex + 0] = rgbData[index + 0];
  10793. rgbaData[newIndex + 1] = rgbData[index + 1];
  10794. rgbaData[newIndex + 2] = rgbData[index + 2];
  10795. // Add fully opaque alpha channel.
  10796. rgbaData[newIndex + 3] = 1;
  10797. }
  10798. }
  10799. return rgbaData;
  10800. };
  10801. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10802. var gl = this._gl;
  10803. if (texture._framebuffer) {
  10804. gl.deleteFramebuffer(texture._framebuffer);
  10805. texture._framebuffer = null;
  10806. }
  10807. if (texture._depthStencilBuffer) {
  10808. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10809. texture._depthStencilBuffer = null;
  10810. }
  10811. if (texture._MSAAFramebuffer) {
  10812. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10813. texture._MSAAFramebuffer = null;
  10814. }
  10815. if (texture._MSAARenderBuffer) {
  10816. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10817. texture._MSAARenderBuffer = null;
  10818. }
  10819. };
  10820. Engine.prototype._releaseTexture = function (texture) {
  10821. var gl = this._gl;
  10822. this._releaseFramebufferObjects(texture);
  10823. gl.deleteTexture(texture._webGLTexture);
  10824. // Unbind channels
  10825. this.unbindAllTextures();
  10826. var index = this._internalTexturesCache.indexOf(texture);
  10827. if (index !== -1) {
  10828. this._internalTexturesCache.splice(index, 1);
  10829. }
  10830. // Integrated fixed lod samplers.
  10831. if (texture._lodTextureHigh) {
  10832. texture._lodTextureHigh.dispose();
  10833. }
  10834. if (texture._lodTextureMid) {
  10835. texture._lodTextureMid.dispose();
  10836. }
  10837. if (texture._lodTextureLow) {
  10838. texture._lodTextureLow.dispose();
  10839. }
  10840. };
  10841. Engine.prototype.setProgram = function (program) {
  10842. if (this._currentProgram !== program) {
  10843. this._gl.useProgram(program);
  10844. this._currentProgram = program;
  10845. }
  10846. };
  10847. Engine.prototype.bindSamplers = function (effect) {
  10848. this.setProgram(effect.getProgram());
  10849. var samplers = effect.getSamplers();
  10850. for (var index = 0; index < samplers.length; index++) {
  10851. var uniform = effect.getUniform(samplers[index]);
  10852. this._gl.uniform1i(uniform, index);
  10853. }
  10854. this._currentEffect = null;
  10855. };
  10856. Engine.prototype.activateTexture = function (texture) {
  10857. if (this._activeTexture !== texture) {
  10858. this._gl.activeTexture(texture);
  10859. this._activeTexture = texture;
  10860. }
  10861. };
  10862. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10863. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10864. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10865. this._activeTexturesCache[this._activeTexture] = texture;
  10866. }
  10867. };
  10868. Engine.prototype._bindTexture = function (channel, texture) {
  10869. if (channel < 0) {
  10870. return;
  10871. }
  10872. this.activateTexture(this._gl.TEXTURE0 + channel);
  10873. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10874. };
  10875. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10876. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10877. };
  10878. Engine.prototype.unbindAllTextures = function () {
  10879. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10880. this.activateTexture(this._gl["TEXTURE" + channel]);
  10881. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10882. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10883. }
  10884. };
  10885. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10886. if (channel < 0) {
  10887. return;
  10888. }
  10889. this._gl.uniform1i(uniform, channel);
  10890. this._setTexture(channel, texture);
  10891. };
  10892. Engine.prototype._setTexture = function (channel, texture) {
  10893. // Not ready?
  10894. if (!texture) {
  10895. if (this._activeTexturesCache[channel] != null) {
  10896. this.activateTexture(this._gl["TEXTURE" + channel]);
  10897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10898. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10899. }
  10900. return;
  10901. }
  10902. // Video
  10903. var alreadyActivated = false;
  10904. if (texture.video) {
  10905. this.activateTexture(this._gl["TEXTURE" + channel]);
  10906. alreadyActivated = true;
  10907. texture.update();
  10908. }
  10909. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10910. texture.delayLoad();
  10911. return;
  10912. }
  10913. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10914. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10915. if (this._activeTexturesCache[channel] === internalTexture) {
  10916. return;
  10917. }
  10918. if (!alreadyActivated) {
  10919. this.activateTexture(this._gl["TEXTURE" + channel]);
  10920. }
  10921. if (internalTexture.isCube) {
  10922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10923. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10924. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10925. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10926. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10927. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10928. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10929. }
  10930. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10931. }
  10932. else {
  10933. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10934. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10935. internalTexture._cachedWrapU = texture.wrapU;
  10936. switch (texture.wrapU) {
  10937. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10939. break;
  10940. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10941. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10942. break;
  10943. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10944. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10945. break;
  10946. }
  10947. }
  10948. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10949. internalTexture._cachedWrapV = texture.wrapV;
  10950. switch (texture.wrapV) {
  10951. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10952. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10953. break;
  10954. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10955. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10956. break;
  10957. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10959. break;
  10960. }
  10961. }
  10962. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10963. }
  10964. };
  10965. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10966. if (channel < 0) {
  10967. return;
  10968. }
  10969. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10970. this._textureUnits = new Int32Array(textures.length);
  10971. }
  10972. for (var i = 0; i < textures.length; i++) {
  10973. this._textureUnits[i] = channel + i;
  10974. }
  10975. this._gl.uniform1iv(uniform, this._textureUnits);
  10976. for (var index = 0; index < textures.length; index++) {
  10977. this._setTexture(channel + index, textures[index]);
  10978. }
  10979. };
  10980. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10981. var internalTexture = texture.getInternalTexture();
  10982. if (!internalTexture) {
  10983. return;
  10984. }
  10985. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10986. var value = texture.anisotropicFilteringLevel;
  10987. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  10988. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  10989. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  10990. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  10991. }
  10992. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10993. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10994. internalTexture._cachedAnisotropicFilteringLevel = value;
  10995. }
  10996. };
  10997. Engine.prototype.readPixels = function (x, y, width, height) {
  10998. var data = new Uint8Array(height * width * 4);
  10999. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11000. return data;
  11001. };
  11002. /**
  11003. * Add an externaly attached data from its key.
  11004. * This method call will fail and return false, if such key already exists.
  11005. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11006. * @param key the unique key that identifies the data
  11007. * @param data the data object to associate to the key for this Engine instance
  11008. * @return true if no such key were already present and the data was added successfully, false otherwise
  11009. */
  11010. Engine.prototype.addExternalData = function (key, data) {
  11011. if (!this._externalData) {
  11012. this._externalData = new BABYLON.StringDictionary();
  11013. }
  11014. return this._externalData.add(key, data);
  11015. };
  11016. /**
  11017. * Get an externaly attached data from its key
  11018. * @param key the unique key that identifies the data
  11019. * @return the associated data, if present (can be null), or undefined if not present
  11020. */
  11021. Engine.prototype.getExternalData = function (key) {
  11022. if (!this._externalData) {
  11023. this._externalData = new BABYLON.StringDictionary();
  11024. }
  11025. return this._externalData.get(key);
  11026. };
  11027. /**
  11028. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11029. * @param key the unique key that identifies the data
  11030. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11031. * @return the associated data, can be null if the factory returned null.
  11032. */
  11033. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11034. if (!this._externalData) {
  11035. this._externalData = new BABYLON.StringDictionary();
  11036. }
  11037. return this._externalData.getOrAddWithFactory(key, factory);
  11038. };
  11039. /**
  11040. * Remove an externaly attached data from the Engine instance
  11041. * @param key the unique key that identifies the data
  11042. * @return true if the data was successfully removed, false if it doesn't exist
  11043. */
  11044. Engine.prototype.removeExternalData = function (key) {
  11045. if (!this._externalData) {
  11046. this._externalData = new BABYLON.StringDictionary();
  11047. }
  11048. return this._externalData.remove(key);
  11049. };
  11050. Engine.prototype.unbindAllAttributes = function () {
  11051. if (this._mustWipeVertexAttributes) {
  11052. this._mustWipeVertexAttributes = false;
  11053. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11054. this._gl.disableVertexAttribArray(i);
  11055. this._vertexAttribArraysEnabled[i] = false;
  11056. this._currentBufferPointers[i].active = false;
  11057. }
  11058. return;
  11059. }
  11060. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11061. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11062. continue;
  11063. }
  11064. this._gl.disableVertexAttribArray(i);
  11065. this._vertexAttribArraysEnabled[i] = false;
  11066. this._currentBufferPointers[i].active = false;
  11067. }
  11068. };
  11069. Engine.prototype.releaseEffects = function () {
  11070. for (var name in this._compiledEffects) {
  11071. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11072. }
  11073. this._compiledEffects = {};
  11074. };
  11075. // Dispose
  11076. Engine.prototype.dispose = function () {
  11077. this.hideLoadingUI();
  11078. this.stopRenderLoop();
  11079. // Release postProcesses
  11080. while (this.postProcesses.length) {
  11081. this.postProcesses[0].dispose();
  11082. }
  11083. // Empty texture
  11084. if (this._emptyTexture) {
  11085. this._releaseTexture(this._emptyTexture);
  11086. this._emptyTexture = null;
  11087. }
  11088. if (this._emptyCubeTexture) {
  11089. this._releaseTexture(this._emptyCubeTexture);
  11090. this._emptyCubeTexture = null;
  11091. }
  11092. // Rescale PP
  11093. if (this._rescalePostProcess) {
  11094. this._rescalePostProcess.dispose();
  11095. }
  11096. // Release scenes
  11097. while (this.scenes.length) {
  11098. this.scenes[0].dispose();
  11099. }
  11100. // Release audio engine
  11101. if (Engine.audioEngine) {
  11102. Engine.audioEngine.dispose();
  11103. }
  11104. // Release effects
  11105. this.releaseEffects();
  11106. // Unbind
  11107. this.unbindAllAttributes();
  11108. if (this._dummyFramebuffer) {
  11109. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11110. }
  11111. this._gl = null;
  11112. //WebVR
  11113. this.disableVR();
  11114. // Events
  11115. window.removeEventListener("blur", this._onBlur);
  11116. window.removeEventListener("focus", this._onFocus);
  11117. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11118. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11119. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11120. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11121. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11122. if (!this._doNotHandleContextLost) {
  11123. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11124. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11125. }
  11126. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11127. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11128. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11129. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11130. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11131. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11132. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11133. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11134. // Remove from Instances
  11135. var index = Engine.Instances.indexOf(this);
  11136. if (index >= 0) {
  11137. Engine.Instances.splice(index, 1);
  11138. }
  11139. this._workingCanvas = null;
  11140. this._workingContext = null;
  11141. this._currentBufferPointers = null;
  11142. this._renderingCanvas = null;
  11143. this._currentProgram = null;
  11144. this.onResizeObservable.clear();
  11145. this.onCanvasBlurObservable.clear();
  11146. this.onCanvasFocusObservable.clear();
  11147. this.onCanvasPointerOutObservable.clear();
  11148. BABYLON.Effect.ResetCache();
  11149. };
  11150. // Loading screen
  11151. Engine.prototype.displayLoadingUI = function () {
  11152. var loadingScreen = this.loadingScreen;
  11153. if (loadingScreen) {
  11154. loadingScreen.displayLoadingUI();
  11155. }
  11156. };
  11157. Engine.prototype.hideLoadingUI = function () {
  11158. var loadingScreen = this.loadingScreen;
  11159. if (loadingScreen) {
  11160. loadingScreen.hideLoadingUI();
  11161. }
  11162. };
  11163. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11164. get: function () {
  11165. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11166. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11167. return this._loadingScreen;
  11168. },
  11169. set: function (loadingScreen) {
  11170. this._loadingScreen = loadingScreen;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11176. set: function (text) {
  11177. this.loadingScreen.loadingUIText = text;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11183. set: function (color) {
  11184. this.loadingScreen.loadingUIBackgroundColor = color;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Engine.prototype.attachContextLostEvent = function (callback) {
  11190. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11191. };
  11192. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11193. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11194. };
  11195. Engine.prototype.getVertexShaderSource = function (program) {
  11196. var shaders = this._gl.getAttachedShaders(program);
  11197. return this._gl.getShaderSource(shaders[0]);
  11198. };
  11199. Engine.prototype.getFragmentShaderSource = function (program) {
  11200. var shaders = this._gl.getAttachedShaders(program);
  11201. return this._gl.getShaderSource(shaders[1]);
  11202. };
  11203. Engine.prototype.getError = function () {
  11204. return this._gl.getError();
  11205. };
  11206. // FPS
  11207. Engine.prototype.getFps = function () {
  11208. return this._fps;
  11209. };
  11210. Engine.prototype.getDeltaTime = function () {
  11211. return this._deltaTime;
  11212. };
  11213. Engine.prototype._measureFps = function () {
  11214. this._performanceMonitor.sampleFrame();
  11215. this._fps = this._performanceMonitor.averageFPS;
  11216. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11217. };
  11218. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11219. if (faceIndex === void 0) { faceIndex = -1; }
  11220. var gl = this._gl;
  11221. if (!this._dummyFramebuffer) {
  11222. this._dummyFramebuffer = gl.createFramebuffer();
  11223. }
  11224. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11225. if (faceIndex > -1) {
  11226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11227. }
  11228. else {
  11229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11230. }
  11231. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11232. var buffer;
  11233. switch (readType) {
  11234. case gl.UNSIGNED_BYTE:
  11235. buffer = new Uint8Array(4 * width * height);
  11236. readType = gl.UNSIGNED_BYTE;
  11237. break;
  11238. default:
  11239. buffer = new Float32Array(4 * width * height);
  11240. readType = gl.FLOAT;
  11241. break;
  11242. }
  11243. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11244. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11245. return buffer;
  11246. };
  11247. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11248. if (this._webGLVersion > 1) {
  11249. return this._caps.colorBufferFloat;
  11250. }
  11251. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11252. };
  11253. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11254. if (this._webGLVersion > 1) {
  11255. return this._caps.colorBufferFloat;
  11256. }
  11257. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11258. };
  11259. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11260. Engine.prototype._canRenderToFramebuffer = function (type) {
  11261. var gl = this._gl;
  11262. //clear existing errors
  11263. while (gl.getError() !== gl.NO_ERROR) { }
  11264. var successful = true;
  11265. var texture = gl.createTexture();
  11266. gl.bindTexture(gl.TEXTURE_2D, texture);
  11267. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11270. var fb = gl.createFramebuffer();
  11271. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11272. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11273. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11274. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11275. successful = successful && (gl.getError() === gl.NO_ERROR);
  11276. //try render by clearing frame buffer's color buffer
  11277. if (successful) {
  11278. gl.clear(gl.COLOR_BUFFER_BIT);
  11279. successful = successful && (gl.getError() === gl.NO_ERROR);
  11280. }
  11281. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11282. if (successful) {
  11283. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11284. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11285. var readFormat = gl.RGBA;
  11286. var readType = gl.UNSIGNED_BYTE;
  11287. var buffer = new Uint8Array(4);
  11288. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11289. successful = successful && (gl.getError() === gl.NO_ERROR);
  11290. }
  11291. //clean up
  11292. gl.deleteTexture(texture);
  11293. gl.deleteFramebuffer(fb);
  11294. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11295. //clear accumulated errors
  11296. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11297. return successful;
  11298. };
  11299. Engine.prototype._getWebGLTextureType = function (type) {
  11300. if (type === Engine.TEXTURETYPE_FLOAT) {
  11301. return this._gl.FLOAT;
  11302. }
  11303. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11304. // Add Half Float Constant.
  11305. return this._gl.HALF_FLOAT_OES;
  11306. }
  11307. return this._gl.UNSIGNED_BYTE;
  11308. };
  11309. ;
  11310. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11311. if (this._webGLVersion === 1) {
  11312. return this._gl.RGBA;
  11313. }
  11314. if (type === Engine.TEXTURETYPE_FLOAT) {
  11315. return this._gl.RGBA32F;
  11316. }
  11317. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11318. return this._gl.RGBA16F;
  11319. }
  11320. return this._gl.RGBA;
  11321. };
  11322. ;
  11323. Engine.prototype.createQuery = function () {
  11324. return this._gl.createQuery();
  11325. };
  11326. Engine.prototype.deleteQuery = function (query) {
  11327. this._gl.deleteQuery(query);
  11328. return this;
  11329. };
  11330. Engine.prototype.isQueryResultAvailable = function (query) {
  11331. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11332. };
  11333. Engine.prototype.getQueryResult = function (query) {
  11334. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11335. };
  11336. Engine.prototype.beginQuery = function (algorithmType, query) {
  11337. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11338. this._gl.beginQuery(glAlgorithm, query);
  11339. };
  11340. Engine.prototype.endQuery = function (algorithmType) {
  11341. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11342. this._gl.endQuery(glAlgorithm);
  11343. return this;
  11344. };
  11345. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11346. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11347. };
  11348. // Statics
  11349. Engine.isSupported = function () {
  11350. try {
  11351. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11352. if (navigator.isCocoonJS) {
  11353. return true;
  11354. }
  11355. var tempcanvas = document.createElement("canvas");
  11356. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11357. return gl != null && !!window.WebGLRenderingContext;
  11358. }
  11359. catch (e) {
  11360. return false;
  11361. }
  11362. };
  11363. Engine.Instances = new Array();
  11364. // Const statics
  11365. Engine._ALPHA_DISABLE = 0;
  11366. Engine._ALPHA_ADD = 1;
  11367. Engine._ALPHA_COMBINE = 2;
  11368. Engine._ALPHA_SUBTRACT = 3;
  11369. Engine._ALPHA_MULTIPLY = 4;
  11370. Engine._ALPHA_MAXIMIZED = 5;
  11371. Engine._ALPHA_ONEONE = 6;
  11372. Engine._ALPHA_PREMULTIPLIED = 7;
  11373. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11374. Engine._ALPHA_INTERPOLATE = 9;
  11375. Engine._ALPHA_SCREENMODE = 10;
  11376. Engine._DELAYLOADSTATE_NONE = 0;
  11377. Engine._DELAYLOADSTATE_LOADED = 1;
  11378. Engine._DELAYLOADSTATE_LOADING = 2;
  11379. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11380. Engine._TEXTUREFORMAT_ALPHA = 0;
  11381. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11382. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11383. Engine._TEXTUREFORMAT_RGB = 4;
  11384. Engine._TEXTUREFORMAT_RGBA = 5;
  11385. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11386. Engine._TEXTURETYPE_FLOAT = 1;
  11387. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11388. // Depht or Stencil test Constants.
  11389. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11390. 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.
  11391. 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.
  11392. 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.
  11393. 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.
  11394. 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.
  11395. 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.
  11396. 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.
  11397. // Stencil Actions Constants.
  11398. Engine._KEEP = 0x1E00;
  11399. Engine._REPLACE = 0x1E01;
  11400. Engine._INCR = 0x1E02;
  11401. Engine._DECR = 0x1E03;
  11402. Engine._INVERT = 0x150A;
  11403. Engine._INCR_WRAP = 0x8507;
  11404. Engine._DECR_WRAP = 0x8508;
  11405. // Texture rescaling mode
  11406. Engine._SCALEMODE_FLOOR = 1;
  11407. Engine._SCALEMODE_NEAREST = 2;
  11408. Engine._SCALEMODE_CEILING = 3;
  11409. // Updatable statics so stick with vars here
  11410. Engine.CollisionsEpsilon = 0.001;
  11411. Engine.CodeRepository = "src/";
  11412. Engine.ShadersRepository = "src/Shaders/";
  11413. return Engine;
  11414. }());
  11415. BABYLON.Engine = Engine;
  11416. })(BABYLON || (BABYLON = {}));
  11417. //# sourceMappingURL=babylon.engine.js.map
  11418. /// <reference path="Tools\babylon.decorators.ts" />
  11419. var BABYLON;
  11420. (function (BABYLON) {
  11421. /**
  11422. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11423. */
  11424. var Node = (function () {
  11425. /**
  11426. * @constructor
  11427. * @param {string} name - the name and id to be given to this node
  11428. * @param {BABYLON.Scene} the scene this node will be added to
  11429. */
  11430. function Node(name, scene) {
  11431. this.state = "";
  11432. this.metadata = null;
  11433. this.doNotSerialize = false;
  11434. this.animations = new Array();
  11435. this._ranges = {};
  11436. this._childrenFlag = -1;
  11437. this._isEnabled = true;
  11438. this._isReady = true;
  11439. this._currentRenderId = -1;
  11440. this._parentRenderId = -1;
  11441. /**
  11442. * An event triggered when the mesh is disposed.
  11443. * @type {BABYLON.Observable}
  11444. */
  11445. this.onDisposeObservable = new BABYLON.Observable();
  11446. // Behaviors
  11447. this._behaviors = new Array();
  11448. this.name = name;
  11449. this.id = name;
  11450. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11451. this._initCache();
  11452. }
  11453. Object.defineProperty(Node.prototype, "parent", {
  11454. get: function () {
  11455. return this._parentNode;
  11456. },
  11457. set: function (parent) {
  11458. if (this._parentNode === parent) {
  11459. return;
  11460. }
  11461. if (this._parentNode) {
  11462. var index = this._parentNode._children.indexOf(this);
  11463. if (index !== -1) {
  11464. this._parentNode._children.splice(index, 1);
  11465. }
  11466. }
  11467. this._parentNode = parent;
  11468. if (this._parentNode) {
  11469. if (!this._parentNode._children) {
  11470. this._parentNode._children = new Array();
  11471. }
  11472. this._parentNode._children.push(this);
  11473. }
  11474. },
  11475. enumerable: true,
  11476. configurable: true
  11477. });
  11478. Node.prototype.getClassName = function () {
  11479. return "Node";
  11480. };
  11481. Object.defineProperty(Node.prototype, "onDispose", {
  11482. set: function (callback) {
  11483. if (this._onDisposeObserver) {
  11484. this.onDisposeObservable.remove(this._onDisposeObserver);
  11485. }
  11486. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11487. },
  11488. enumerable: true,
  11489. configurable: true
  11490. });
  11491. Node.prototype.getScene = function () {
  11492. return this._scene;
  11493. };
  11494. Node.prototype.getEngine = function () {
  11495. return this._scene.getEngine();
  11496. };
  11497. Node.prototype.addBehavior = function (behavior) {
  11498. var index = this._behaviors.indexOf(behavior);
  11499. if (index !== -1) {
  11500. return;
  11501. }
  11502. behavior.attach(this);
  11503. this._behaviors.push(behavior);
  11504. return this;
  11505. };
  11506. Node.prototype.removeBehavior = function (behavior) {
  11507. var index = this._behaviors.indexOf(behavior);
  11508. if (index === -1) {
  11509. return;
  11510. }
  11511. this._behaviors[index].detach();
  11512. this._behaviors.splice(index, 1);
  11513. return this;
  11514. };
  11515. Object.defineProperty(Node.prototype, "behaviors", {
  11516. get: function () {
  11517. return this._behaviors;
  11518. },
  11519. enumerable: true,
  11520. configurable: true
  11521. });
  11522. Node.prototype.getBehaviorByName = function (name) {
  11523. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11524. var behavior = _a[_i];
  11525. if (behavior.name === name) {
  11526. return behavior;
  11527. }
  11528. }
  11529. return null;
  11530. };
  11531. // override it in derived class
  11532. Node.prototype.getWorldMatrix = function () {
  11533. return BABYLON.Matrix.Identity();
  11534. };
  11535. // override it in derived class if you add new variables to the cache
  11536. // and call the parent class method
  11537. Node.prototype._initCache = function () {
  11538. this._cache = {};
  11539. this._cache.parent = undefined;
  11540. };
  11541. Node.prototype.updateCache = function (force) {
  11542. if (!force && this.isSynchronized())
  11543. return;
  11544. this._cache.parent = this.parent;
  11545. this._updateCache();
  11546. };
  11547. // override it in derived class if you add new variables to the cache
  11548. // and call the parent class method if !ignoreParentClass
  11549. Node.prototype._updateCache = function (ignoreParentClass) {
  11550. };
  11551. // override it in derived class if you add new variables to the cache
  11552. Node.prototype._isSynchronized = function () {
  11553. return true;
  11554. };
  11555. Node.prototype._markSyncedWithParent = function () {
  11556. this._parentRenderId = this.parent._currentRenderId;
  11557. };
  11558. Node.prototype.isSynchronizedWithParent = function () {
  11559. if (!this.parent) {
  11560. return true;
  11561. }
  11562. if (this._parentRenderId !== this.parent._currentRenderId) {
  11563. return false;
  11564. }
  11565. return this.parent.isSynchronized();
  11566. };
  11567. Node.prototype.isSynchronized = function (updateCache) {
  11568. var check = this.hasNewParent();
  11569. check = check || !this.isSynchronizedWithParent();
  11570. check = check || !this._isSynchronized();
  11571. if (updateCache)
  11572. this.updateCache(true);
  11573. return !check;
  11574. };
  11575. Node.prototype.hasNewParent = function (update) {
  11576. if (this._cache.parent === this.parent)
  11577. return false;
  11578. if (update)
  11579. this._cache.parent = this.parent;
  11580. return true;
  11581. };
  11582. /**
  11583. * Is this node ready to be used/rendered
  11584. * @return {boolean} is it ready
  11585. */
  11586. Node.prototype.isReady = function () {
  11587. return this._isReady;
  11588. };
  11589. /**
  11590. * Is this node enabled.
  11591. * If the node has a parent and is enabled, the parent will be inspected as well.
  11592. * @return {boolean} whether this node (and its parent) is enabled.
  11593. * @see setEnabled
  11594. */
  11595. Node.prototype.isEnabled = function () {
  11596. if (!this._isEnabled) {
  11597. return false;
  11598. }
  11599. if (this.parent) {
  11600. return this.parent.isEnabled();
  11601. }
  11602. return true;
  11603. };
  11604. /**
  11605. * Set the enabled state of this node.
  11606. * @param {boolean} value - the new enabled state
  11607. * @see isEnabled
  11608. */
  11609. Node.prototype.setEnabled = function (value) {
  11610. this._isEnabled = value;
  11611. };
  11612. /**
  11613. * Is this node a descendant of the given node.
  11614. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11615. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11616. * @see parent
  11617. */
  11618. Node.prototype.isDescendantOf = function (ancestor) {
  11619. if (this.parent) {
  11620. if (this.parent === ancestor) {
  11621. return true;
  11622. }
  11623. return this.parent.isDescendantOf(ancestor);
  11624. }
  11625. return false;
  11626. };
  11627. /**
  11628. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11629. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11630. * @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.
  11631. * @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.
  11632. */
  11633. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11634. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11635. if (!this._children) {
  11636. return;
  11637. }
  11638. for (var index = 0; index < this._children.length; index++) {
  11639. var item = this._children[index];
  11640. if (!predicate || predicate(item)) {
  11641. results.push(item);
  11642. }
  11643. if (!directDescendantsOnly) {
  11644. item._getDescendants(results, false, predicate);
  11645. }
  11646. }
  11647. };
  11648. /**
  11649. * Will return all nodes that have this node as ascendant.
  11650. * @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.
  11651. * @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.
  11652. * @return {BABYLON.Node[]} all children nodes of all types.
  11653. */
  11654. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11655. var results = [];
  11656. this._getDescendants(results, directDescendantsOnly, predicate);
  11657. return results;
  11658. };
  11659. /**
  11660. * Get all child-meshes of this node.
  11661. */
  11662. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11663. var results = [];
  11664. this._getDescendants(results, directDecendantsOnly, function (node) {
  11665. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11666. });
  11667. return results;
  11668. };
  11669. /**
  11670. * Get all direct children of this node.
  11671. */
  11672. Node.prototype.getChildren = function (predicate) {
  11673. return this.getDescendants(true, predicate);
  11674. };
  11675. Node.prototype._setReady = function (state) {
  11676. if (state === this._isReady) {
  11677. return;
  11678. }
  11679. if (!state) {
  11680. this._isReady = false;
  11681. return;
  11682. }
  11683. this._isReady = true;
  11684. if (this.onReady) {
  11685. this.onReady(this);
  11686. }
  11687. };
  11688. Node.prototype.getAnimationByName = function (name) {
  11689. for (var i = 0; i < this.animations.length; i++) {
  11690. var animation = this.animations[i];
  11691. if (animation.name === name) {
  11692. return animation;
  11693. }
  11694. }
  11695. return null;
  11696. };
  11697. Node.prototype.createAnimationRange = function (name, from, to) {
  11698. // check name not already in use
  11699. if (!this._ranges[name]) {
  11700. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11701. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11702. if (this.animations[i]) {
  11703. this.animations[i].createRange(name, from, to);
  11704. }
  11705. }
  11706. }
  11707. };
  11708. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11709. if (deleteFrames === void 0) { deleteFrames = true; }
  11710. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11711. if (this.animations[i]) {
  11712. this.animations[i].deleteRange(name, deleteFrames);
  11713. }
  11714. }
  11715. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11716. };
  11717. Node.prototype.getAnimationRange = function (name) {
  11718. return this._ranges[name];
  11719. };
  11720. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11721. var range = this.getAnimationRange(name);
  11722. if (!range) {
  11723. return null;
  11724. }
  11725. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11726. };
  11727. Node.prototype.serializeAnimationRanges = function () {
  11728. var serializationRanges = [];
  11729. for (var name in this._ranges) {
  11730. var range = {};
  11731. range.name = name;
  11732. range.from = this._ranges[name].from;
  11733. range.to = this._ranges[name].to;
  11734. serializationRanges.push(range);
  11735. }
  11736. return serializationRanges;
  11737. };
  11738. Node.prototype.dispose = function () {
  11739. this.parent = null;
  11740. // Callback
  11741. this.onDisposeObservable.notifyObservers(this);
  11742. this.onDisposeObservable.clear();
  11743. // Behaviors
  11744. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11745. var behavior = _a[_i];
  11746. behavior.detach();
  11747. }
  11748. this._behaviors = [];
  11749. };
  11750. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11751. if (parsedNode.ranges) {
  11752. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11753. var data = parsedNode.ranges[index];
  11754. node.createAnimationRange(data.name, data.from, data.to);
  11755. }
  11756. }
  11757. };
  11758. __decorate([
  11759. BABYLON.serialize()
  11760. ], Node.prototype, "name", void 0);
  11761. __decorate([
  11762. BABYLON.serialize()
  11763. ], Node.prototype, "id", void 0);
  11764. __decorate([
  11765. BABYLON.serialize()
  11766. ], Node.prototype, "uniqueId", void 0);
  11767. __decorate([
  11768. BABYLON.serialize()
  11769. ], Node.prototype, "state", void 0);
  11770. __decorate([
  11771. BABYLON.serialize()
  11772. ], Node.prototype, "metadata", void 0);
  11773. return Node;
  11774. }());
  11775. BABYLON.Node = Node;
  11776. })(BABYLON || (BABYLON = {}));
  11777. //# sourceMappingURL=babylon.node.js.map
  11778. var BABYLON;
  11779. (function (BABYLON) {
  11780. var BoundingSphere = (function () {
  11781. function BoundingSphere(minimum, maximum) {
  11782. this.minimum = minimum;
  11783. this.maximum = maximum;
  11784. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11785. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11786. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11787. this.radius = distance * 0.5;
  11788. this.centerWorld = BABYLON.Vector3.Zero();
  11789. this._update(BABYLON.Matrix.Identity());
  11790. }
  11791. // Methods
  11792. BoundingSphere.prototype._update = function (world) {
  11793. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11794. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11795. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11796. };
  11797. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11798. for (var i = 0; i < 6; i++) {
  11799. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11800. return false;
  11801. }
  11802. return true;
  11803. };
  11804. BoundingSphere.prototype.intersectsPoint = function (point) {
  11805. var x = this.centerWorld.x - point.x;
  11806. var y = this.centerWorld.y - point.y;
  11807. var z = this.centerWorld.z - point.z;
  11808. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11809. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11810. return false;
  11811. return true;
  11812. };
  11813. // Statics
  11814. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11815. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11816. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11817. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11818. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11819. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11820. return false;
  11821. return true;
  11822. };
  11823. return BoundingSphere;
  11824. }());
  11825. BABYLON.BoundingSphere = BoundingSphere;
  11826. })(BABYLON || (BABYLON = {}));
  11827. //# sourceMappingURL=babylon.boundingSphere.js.map
  11828. var BABYLON;
  11829. (function (BABYLON) {
  11830. var BoundingBox = (function () {
  11831. function BoundingBox(minimum, maximum) {
  11832. this.minimum = minimum;
  11833. this.maximum = maximum;
  11834. this.vectors = new Array();
  11835. this.vectorsWorld = new Array();
  11836. // Bounding vectors
  11837. this.vectors.push(this.minimum.clone());
  11838. this.vectors.push(this.maximum.clone());
  11839. this.vectors.push(this.minimum.clone());
  11840. this.vectors[2].x = this.maximum.x;
  11841. this.vectors.push(this.minimum.clone());
  11842. this.vectors[3].y = this.maximum.y;
  11843. this.vectors.push(this.minimum.clone());
  11844. this.vectors[4].z = this.maximum.z;
  11845. this.vectors.push(this.maximum.clone());
  11846. this.vectors[5].z = this.minimum.z;
  11847. this.vectors.push(this.maximum.clone());
  11848. this.vectors[6].x = this.minimum.x;
  11849. this.vectors.push(this.maximum.clone());
  11850. this.vectors[7].y = this.minimum.y;
  11851. // OBB
  11852. this.center = this.maximum.add(this.minimum).scale(0.5);
  11853. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11854. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11855. // World
  11856. for (var index = 0; index < this.vectors.length; index++) {
  11857. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11858. }
  11859. this.minimumWorld = BABYLON.Vector3.Zero();
  11860. this.maximumWorld = BABYLON.Vector3.Zero();
  11861. this.centerWorld = BABYLON.Vector3.Zero();
  11862. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11863. this._update(BABYLON.Matrix.Identity());
  11864. }
  11865. // Methods
  11866. BoundingBox.prototype.getWorldMatrix = function () {
  11867. return this._worldMatrix;
  11868. };
  11869. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11870. this._worldMatrix.copyFrom(matrix);
  11871. return this;
  11872. };
  11873. BoundingBox.prototype._update = function (world) {
  11874. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11875. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11876. for (var index = 0; index < this.vectors.length; index++) {
  11877. var v = this.vectorsWorld[index];
  11878. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11879. if (v.x < this.minimumWorld.x)
  11880. this.minimumWorld.x = v.x;
  11881. if (v.y < this.minimumWorld.y)
  11882. this.minimumWorld.y = v.y;
  11883. if (v.z < this.minimumWorld.z)
  11884. this.minimumWorld.z = v.z;
  11885. if (v.x > this.maximumWorld.x)
  11886. this.maximumWorld.x = v.x;
  11887. if (v.y > this.maximumWorld.y)
  11888. this.maximumWorld.y = v.y;
  11889. if (v.z > this.maximumWorld.z)
  11890. this.maximumWorld.z = v.z;
  11891. }
  11892. // Extend
  11893. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11894. this.extendSizeWorld.scaleInPlace(0.5);
  11895. // OBB
  11896. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11897. this.centerWorld.scaleInPlace(0.5);
  11898. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11899. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11900. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11901. this._worldMatrix = world;
  11902. };
  11903. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11904. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11905. };
  11906. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11907. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11908. };
  11909. BoundingBox.prototype.intersectsPoint = function (point) {
  11910. var delta = -BABYLON.Epsilon;
  11911. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11912. return false;
  11913. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11914. return false;
  11915. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11916. return false;
  11917. return true;
  11918. };
  11919. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11920. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11921. };
  11922. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11923. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11924. return false;
  11925. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11926. return false;
  11927. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11928. return false;
  11929. return true;
  11930. };
  11931. // Statics
  11932. BoundingBox.Intersects = function (box0, box1) {
  11933. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11934. return false;
  11935. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11936. return false;
  11937. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11938. return false;
  11939. return true;
  11940. };
  11941. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11942. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11943. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11944. return (num <= (sphereRadius * sphereRadius));
  11945. };
  11946. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11947. for (var p = 0; p < 6; p++) {
  11948. for (var i = 0; i < 8; i++) {
  11949. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11950. return false;
  11951. }
  11952. }
  11953. }
  11954. return true;
  11955. };
  11956. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11957. for (var p = 0; p < 6; p++) {
  11958. var inCount = 8;
  11959. for (var i = 0; i < 8; i++) {
  11960. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11961. --inCount;
  11962. }
  11963. else {
  11964. break;
  11965. }
  11966. }
  11967. if (inCount === 0)
  11968. return false;
  11969. }
  11970. return true;
  11971. };
  11972. return BoundingBox;
  11973. }());
  11974. BABYLON.BoundingBox = BoundingBox;
  11975. })(BABYLON || (BABYLON = {}));
  11976. //# sourceMappingURL=babylon.boundingBox.js.map
  11977. var BABYLON;
  11978. (function (BABYLON) {
  11979. var computeBoxExtents = function (axis, box) {
  11980. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11981. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11982. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11983. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11984. var r = r0 + r1 + r2;
  11985. return {
  11986. min: p - r,
  11987. max: p + r
  11988. };
  11989. };
  11990. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11991. var axisOverlap = function (axis, box0, box1) {
  11992. var result0 = computeBoxExtents(axis, box0);
  11993. var result1 = computeBoxExtents(axis, box1);
  11994. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11995. };
  11996. var BoundingInfo = (function () {
  11997. function BoundingInfo(minimum, maximum) {
  11998. this.minimum = minimum;
  11999. this.maximum = maximum;
  12000. this._isLocked = false;
  12001. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12002. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12003. }
  12004. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12005. get: function () {
  12006. return this._isLocked;
  12007. },
  12008. set: function (value) {
  12009. this._isLocked = value;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. // Methods
  12015. BoundingInfo.prototype.update = function (world) {
  12016. if (this._isLocked) {
  12017. return;
  12018. }
  12019. this.boundingBox._update(world);
  12020. this.boundingSphere._update(world);
  12021. };
  12022. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12023. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12024. return false;
  12025. return this.boundingBox.isInFrustum(frustumPlanes);
  12026. };
  12027. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12028. /**
  12029. * Gets the world distance between the min and max points of the bounding box
  12030. */
  12031. get: function () {
  12032. var boundingBox = this.boundingBox;
  12033. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12034. return size.length();
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12040. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12041. };
  12042. BoundingInfo.prototype._checkCollision = function (collider) {
  12043. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12044. };
  12045. BoundingInfo.prototype.intersectsPoint = function (point) {
  12046. if (!this.boundingSphere.centerWorld) {
  12047. return false;
  12048. }
  12049. if (!this.boundingSphere.intersectsPoint(point)) {
  12050. return false;
  12051. }
  12052. if (!this.boundingBox.intersectsPoint(point)) {
  12053. return false;
  12054. }
  12055. return true;
  12056. };
  12057. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12058. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12059. return false;
  12060. }
  12061. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12062. return false;
  12063. }
  12064. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12065. return false;
  12066. }
  12067. if (!precise) {
  12068. return true;
  12069. }
  12070. var box0 = this.boundingBox;
  12071. var box1 = boundingInfo.boundingBox;
  12072. if (!axisOverlap(box0.directions[0], box0, box1))
  12073. return false;
  12074. if (!axisOverlap(box0.directions[1], box0, box1))
  12075. return false;
  12076. if (!axisOverlap(box0.directions[2], box0, box1))
  12077. return false;
  12078. if (!axisOverlap(box1.directions[0], box0, box1))
  12079. return false;
  12080. if (!axisOverlap(box1.directions[1], box0, box1))
  12081. return false;
  12082. if (!axisOverlap(box1.directions[2], box0, box1))
  12083. return false;
  12084. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12085. return false;
  12086. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12087. return false;
  12088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12089. return false;
  12090. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12091. return false;
  12092. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12093. return false;
  12094. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12095. return false;
  12096. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12097. return false;
  12098. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12099. return false;
  12100. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12101. return false;
  12102. return true;
  12103. };
  12104. return BoundingInfo;
  12105. }());
  12106. BABYLON.BoundingInfo = BoundingInfo;
  12107. })(BABYLON || (BABYLON = {}));
  12108. //# sourceMappingURL=babylon.boundingInfo.js.map
  12109. var BABYLON;
  12110. (function (BABYLON) {
  12111. var AbstractMesh = (function (_super) {
  12112. __extends(AbstractMesh, _super);
  12113. // Constructor
  12114. function AbstractMesh(name, scene) {
  12115. var _this = _super.call(this, name, scene) || this;
  12116. _this._facetNb = 0; // facet number
  12117. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12118. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12119. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12120. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12121. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12122. _this._subDiv = {
  12123. max: 1,
  12124. X: 1,
  12125. Y: 1,
  12126. Z: 1
  12127. };
  12128. // Events
  12129. /**
  12130. * An event triggered when this mesh collides with another one
  12131. * @type {BABYLON.Observable}
  12132. */
  12133. _this.onCollideObservable = new BABYLON.Observable();
  12134. /**
  12135. * An event triggered when the collision's position changes
  12136. * @type {BABYLON.Observable}
  12137. */
  12138. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12139. /**
  12140. * An event triggered after the world matrix is updated
  12141. * @type {BABYLON.Observable}
  12142. */
  12143. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12144. /**
  12145. * An event triggered when material is changed
  12146. * @type {BABYLON.Observable}
  12147. */
  12148. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12149. // Properties
  12150. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12151. _this.position = BABYLON.Vector3.Zero();
  12152. /**
  12153. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12154. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12155. * or
  12156. * 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.
  12157. * for more info check WebGl documentations
  12158. */
  12159. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12160. /**
  12161. * 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:
  12162. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12163. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12164. * 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.
  12165. */
  12166. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12167. /**
  12168. * 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.
  12169. * The default value is -1 which means don't break the query and wait till the result.
  12170. */
  12171. _this.occlusionRetryCount = -1;
  12172. _this._occlusionInternalRetryCounter = 0;
  12173. _this._isOccluded = false;
  12174. _this._isOcclusionQueryInProgress = false;
  12175. _this._rotation = BABYLON.Vector3.Zero();
  12176. _this._scaling = BABYLON.Vector3.One();
  12177. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12178. _this.visibility = 1.0;
  12179. _this.alphaIndex = Number.MAX_VALUE;
  12180. _this.infiniteDistance = false;
  12181. _this.isVisible = true;
  12182. _this.isPickable = true;
  12183. _this.showBoundingBox = false;
  12184. _this.showSubMeshesBoundingBox = false;
  12185. _this.isBlocker = false;
  12186. _this.enablePointerMoveEvents = false;
  12187. _this.renderingGroupId = 0;
  12188. _this._receiveShadows = false;
  12189. _this.renderOutline = false;
  12190. _this.outlineColor = BABYLON.Color3.Red();
  12191. _this.outlineWidth = 0.02;
  12192. _this.renderOverlay = false;
  12193. _this.overlayColor = BABYLON.Color3.Red();
  12194. _this.overlayAlpha = 0.5;
  12195. _this._hasVertexAlpha = false;
  12196. _this._useVertexColors = true;
  12197. _this._computeBonesUsingShaders = true;
  12198. _this._numBoneInfluencers = 4;
  12199. _this._applyFog = true;
  12200. _this.scalingDeterminant = 1;
  12201. _this.useOctreeForRenderingSelection = true;
  12202. _this.useOctreeForPicking = true;
  12203. _this.useOctreeForCollisions = true;
  12204. _this._layerMask = 0x0FFFFFFF;
  12205. /**
  12206. * True if the mesh must be rendered in any case.
  12207. */
  12208. _this.alwaysSelectAsActiveMesh = false;
  12209. // Collisions
  12210. _this._checkCollisions = false;
  12211. _this._collisionMask = -1;
  12212. _this._collisionGroup = -1;
  12213. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12214. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12215. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12216. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12217. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12218. // Edges
  12219. _this.edgesWidth = 1;
  12220. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12221. // Cache
  12222. _this._localWorld = BABYLON.Matrix.Zero();
  12223. _this._worldMatrix = BABYLON.Matrix.Zero();
  12224. _this._absolutePosition = BABYLON.Vector3.Zero();
  12225. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12226. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12227. _this._isDirty = false;
  12228. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12229. _this._isDisposed = false;
  12230. _this._renderId = 0;
  12231. _this._intersectionsInProgress = new Array();
  12232. _this._isWorldMatrixFrozen = false;
  12233. _this._unIndexed = false;
  12234. _this._lightSources = new Array();
  12235. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12236. if (collidedMesh === void 0) { collidedMesh = null; }
  12237. //TODO move this to the collision coordinator!
  12238. if (_this.getScene().workerCollisions)
  12239. newPosition.multiplyInPlace(_this._collider.radius);
  12240. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12241. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12242. _this.position.addInPlace(_this._diffPositionForCollisions);
  12243. }
  12244. if (collidedMesh) {
  12245. _this.onCollideObservable.notifyObservers(collidedMesh);
  12246. }
  12247. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12248. };
  12249. _this.getScene().addMesh(_this);
  12250. _this._resyncLightSources();
  12251. return _this;
  12252. }
  12253. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12254. get: function () {
  12255. return AbstractMesh._BILLBOARDMODE_NONE;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12261. get: function () {
  12262. return AbstractMesh._BILLBOARDMODE_X;
  12263. },
  12264. enumerable: true,
  12265. configurable: true
  12266. });
  12267. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12268. get: function () {
  12269. return AbstractMesh._BILLBOARDMODE_Y;
  12270. },
  12271. enumerable: true,
  12272. configurable: true
  12273. });
  12274. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12275. get: function () {
  12276. return AbstractMesh._BILLBOARDMODE_Z;
  12277. },
  12278. enumerable: true,
  12279. configurable: true
  12280. });
  12281. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12282. get: function () {
  12283. return AbstractMesh._BILLBOARDMODE_ALL;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12289. /**
  12290. * Read-only : the number of facets in the mesh
  12291. */
  12292. get: function () {
  12293. return this._facetNb;
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12299. /**
  12300. * The number (integer) of subdivisions per axis in the partioning space
  12301. */
  12302. get: function () {
  12303. return this._partitioningSubdivisions;
  12304. },
  12305. set: function (nb) {
  12306. this._partitioningSubdivisions = nb;
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12312. /**
  12313. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12314. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12315. */
  12316. get: function () {
  12317. return this._partitioningBBoxRatio;
  12318. },
  12319. set: function (ratio) {
  12320. this._partitioningBBoxRatio = ratio;
  12321. },
  12322. enumerable: true,
  12323. configurable: true
  12324. });
  12325. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12326. /**
  12327. * Read-only boolean : is the feature facetData enabled ?
  12328. */
  12329. get: function () {
  12330. return this._facetDataEnabled;
  12331. },
  12332. enumerable: true,
  12333. configurable: true
  12334. });
  12335. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12336. set: function (callback) {
  12337. if (this._onCollideObserver) {
  12338. this.onCollideObservable.remove(this._onCollideObserver);
  12339. }
  12340. this._onCollideObserver = this.onCollideObservable.add(callback);
  12341. },
  12342. enumerable: true,
  12343. configurable: true
  12344. });
  12345. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12346. set: function (callback) {
  12347. if (this._onCollisionPositionChangeObserver) {
  12348. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12349. }
  12350. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12356. /**
  12357. * 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.
  12358. */
  12359. get: function () {
  12360. return this._isOccluded;
  12361. },
  12362. set: function (value) {
  12363. this._isOccluded = value;
  12364. },
  12365. enumerable: true,
  12366. configurable: true
  12367. });
  12368. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12369. /**
  12370. * Flag to check the progress status of the query
  12371. */
  12372. get: function () {
  12373. return this._isOcclusionQueryInProgress;
  12374. },
  12375. enumerable: true,
  12376. configurable: true
  12377. });
  12378. Object.defineProperty(AbstractMesh.prototype, "material", {
  12379. get: function () {
  12380. return this._material;
  12381. },
  12382. set: function (value) {
  12383. if (this._material === value) {
  12384. return;
  12385. }
  12386. this._material = value;
  12387. if (this.onMaterialChangedObservable.hasObservers) {
  12388. this.onMaterialChangedObservable.notifyObservers(this);
  12389. }
  12390. if (!this.subMeshes) {
  12391. return;
  12392. }
  12393. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12394. var subMesh = _a[_i];
  12395. subMesh.setEffect(null);
  12396. }
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12402. get: function () {
  12403. return this._receiveShadows;
  12404. },
  12405. set: function (value) {
  12406. if (this._receiveShadows === value) {
  12407. return;
  12408. }
  12409. this._receiveShadows = value;
  12410. this._markSubMeshesAsLightDirty();
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12416. get: function () {
  12417. return this._hasVertexAlpha;
  12418. },
  12419. set: function (value) {
  12420. if (this._hasVertexAlpha === value) {
  12421. return;
  12422. }
  12423. this._hasVertexAlpha = value;
  12424. this._markSubMeshesAsAttributesDirty();
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12430. get: function () {
  12431. return this._useVertexColors;
  12432. },
  12433. set: function (value) {
  12434. if (this._useVertexColors === value) {
  12435. return;
  12436. }
  12437. this._useVertexColors = value;
  12438. this._markSubMeshesAsAttributesDirty();
  12439. },
  12440. enumerable: true,
  12441. configurable: true
  12442. });
  12443. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12444. get: function () {
  12445. return this._computeBonesUsingShaders;
  12446. },
  12447. set: function (value) {
  12448. if (this._computeBonesUsingShaders === value) {
  12449. return;
  12450. }
  12451. this._computeBonesUsingShaders = value;
  12452. this._markSubMeshesAsAttributesDirty();
  12453. },
  12454. enumerable: true,
  12455. configurable: true
  12456. });
  12457. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12458. get: function () {
  12459. return this._numBoneInfluencers;
  12460. },
  12461. set: function (value) {
  12462. if (this._numBoneInfluencers === value) {
  12463. return;
  12464. }
  12465. this._numBoneInfluencers = value;
  12466. this._markSubMeshesAsAttributesDirty();
  12467. },
  12468. enumerable: true,
  12469. configurable: true
  12470. });
  12471. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12472. get: function () {
  12473. return this._applyFog;
  12474. },
  12475. set: function (value) {
  12476. if (this._applyFog === value) {
  12477. return;
  12478. }
  12479. this._applyFog = value;
  12480. this._markSubMeshesAsMiscDirty();
  12481. },
  12482. enumerable: true,
  12483. configurable: true
  12484. });
  12485. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12486. get: function () {
  12487. return this._layerMask;
  12488. },
  12489. set: function (value) {
  12490. if (value === this._layerMask) {
  12491. return;
  12492. }
  12493. this._layerMask = value;
  12494. this._resyncLightSources();
  12495. },
  12496. enumerable: true,
  12497. configurable: true
  12498. });
  12499. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12500. get: function () {
  12501. return this._collisionMask;
  12502. },
  12503. set: function (mask) {
  12504. this._collisionMask = !isNaN(mask) ? mask : -1;
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12510. get: function () {
  12511. return this._collisionGroup;
  12512. },
  12513. set: function (mask) {
  12514. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12515. },
  12516. enumerable: true,
  12517. configurable: true
  12518. });
  12519. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12520. get: function () {
  12521. return null;
  12522. },
  12523. enumerable: true,
  12524. configurable: true
  12525. });
  12526. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12527. get: function () {
  12528. return this._skeleton;
  12529. },
  12530. set: function (value) {
  12531. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12532. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12533. }
  12534. if (value && value.needInitialSkinMatrix) {
  12535. value._registerMeshWithPoseMatrix(this);
  12536. }
  12537. this._skeleton = value;
  12538. if (!this._skeleton) {
  12539. this._bonesTransformMatrices = null;
  12540. }
  12541. this._markSubMeshesAsAttributesDirty();
  12542. },
  12543. enumerable: true,
  12544. configurable: true
  12545. });
  12546. /**
  12547. * Boolean : true if the mesh has been disposed.
  12548. */
  12549. AbstractMesh.prototype.isDisposed = function () {
  12550. return this._isDisposed;
  12551. };
  12552. /**
  12553. * Returns the string "AbstractMesh"
  12554. */
  12555. AbstractMesh.prototype.getClassName = function () {
  12556. return "AbstractMesh";
  12557. };
  12558. /**
  12559. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12560. */
  12561. AbstractMesh.prototype.toString = function (fullDetails) {
  12562. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12563. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12564. if (this._skeleton) {
  12565. ret += ", skeleton: " + this._skeleton.name;
  12566. }
  12567. if (fullDetails) {
  12568. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12569. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12570. }
  12571. return ret;
  12572. };
  12573. AbstractMesh.prototype._rebuild = function () {
  12574. if (this._occlusionQuery) {
  12575. this._occlusionQuery = null;
  12576. }
  12577. if (this._edgesRenderer) {
  12578. this._edgesRenderer._rebuild();
  12579. }
  12580. if (!this.subMeshes) {
  12581. return;
  12582. }
  12583. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12584. var subMesh = _a[_i];
  12585. subMesh._rebuild();
  12586. }
  12587. };
  12588. AbstractMesh.prototype._resyncLightSources = function () {
  12589. this._lightSources.length = 0;
  12590. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12591. var light = _a[_i];
  12592. if (!light.isEnabled()) {
  12593. continue;
  12594. }
  12595. if (light.canAffectMesh(this)) {
  12596. this._lightSources.push(light);
  12597. }
  12598. }
  12599. this._markSubMeshesAsLightDirty();
  12600. };
  12601. AbstractMesh.prototype._resyncLighSource = function (light) {
  12602. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12603. var index = this._lightSources.indexOf(light);
  12604. if (index === -1) {
  12605. if (!isIn) {
  12606. return;
  12607. }
  12608. this._lightSources.push(light);
  12609. }
  12610. else {
  12611. if (isIn) {
  12612. return;
  12613. }
  12614. this._lightSources.splice(index, 1);
  12615. }
  12616. this._markSubMeshesAsLightDirty();
  12617. };
  12618. AbstractMesh.prototype._removeLightSource = function (light) {
  12619. var index = this._lightSources.indexOf(light);
  12620. if (index === -1) {
  12621. return;
  12622. }
  12623. this._lightSources.splice(index, 1);
  12624. };
  12625. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12626. if (!this.subMeshes) {
  12627. return;
  12628. }
  12629. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12630. var subMesh = _a[_i];
  12631. if (subMesh._materialDefines) {
  12632. func(subMesh._materialDefines);
  12633. }
  12634. }
  12635. };
  12636. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12637. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12638. };
  12639. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12640. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12641. };
  12642. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12643. if (!this.subMeshes) {
  12644. return;
  12645. }
  12646. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12647. var subMesh = _a[_i];
  12648. var material = subMesh.getMaterial();
  12649. if (material) {
  12650. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12651. }
  12652. }
  12653. };
  12654. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12655. /**
  12656. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12657. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12658. * Default : (0.0, 0.0, 0.0)
  12659. */
  12660. get: function () {
  12661. return this._rotation;
  12662. },
  12663. set: function (newRotation) {
  12664. this._rotation = newRotation;
  12665. },
  12666. enumerable: true,
  12667. configurable: true
  12668. });
  12669. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12670. /**
  12671. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12672. * Default : (1.0, 1.0, 1.0)
  12673. */
  12674. get: function () {
  12675. return this._scaling;
  12676. },
  12677. set: function (newScaling) {
  12678. this._scaling = newScaling;
  12679. if (this.physicsImpostor) {
  12680. this.physicsImpostor.forceUpdate();
  12681. }
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12687. /**
  12688. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12689. * It's null by default.
  12690. * 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)
  12691. */
  12692. get: function () {
  12693. return this._rotationQuaternion;
  12694. },
  12695. set: function (quaternion) {
  12696. this._rotationQuaternion = quaternion;
  12697. //reset the rotation vector.
  12698. if (quaternion && this.rotation.length()) {
  12699. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12700. }
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. // Methods
  12706. /**
  12707. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12708. * Returns the AbstractMesh.
  12709. */
  12710. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12711. this._poseMatrix.copyFrom(matrix);
  12712. return this;
  12713. };
  12714. /**
  12715. * Returns the mesh Pose matrix.
  12716. * Returned object : Matrix
  12717. */
  12718. AbstractMesh.prototype.getPoseMatrix = function () {
  12719. return this._poseMatrix;
  12720. };
  12721. /**
  12722. * Disables the mesh edger rendering mode.
  12723. * Returns the AbstractMesh.
  12724. */
  12725. AbstractMesh.prototype.disableEdgesRendering = function () {
  12726. if (this._edgesRenderer !== undefined) {
  12727. this._edgesRenderer.dispose();
  12728. this._edgesRenderer = undefined;
  12729. }
  12730. return this;
  12731. };
  12732. /**
  12733. * Enables the edge rendering mode on the mesh.
  12734. * This mode makes the mesh edges visible.
  12735. * Returns the AbstractMesh.
  12736. */
  12737. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12738. if (epsilon === void 0) { epsilon = 0.95; }
  12739. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12740. this.disableEdgesRendering();
  12741. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12742. return this;
  12743. };
  12744. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12745. /**
  12746. * Returns true if the mesh is blocked. Used by the class Mesh.
  12747. * Returns the boolean `false` by default.
  12748. */
  12749. get: function () {
  12750. return false;
  12751. },
  12752. enumerable: true,
  12753. configurable: true
  12754. });
  12755. /**
  12756. * Returns the mesh itself by default, used by the class Mesh.
  12757. * Returned type : AbstractMesh
  12758. */
  12759. AbstractMesh.prototype.getLOD = function (camera) {
  12760. return this;
  12761. };
  12762. /**
  12763. * Returns 0 by default, used by the class Mesh.
  12764. * Returns an integer.
  12765. */
  12766. AbstractMesh.prototype.getTotalVertices = function () {
  12767. return 0;
  12768. };
  12769. /**
  12770. * Returns null by default, used by the class Mesh.
  12771. * Returned type : integer array
  12772. */
  12773. AbstractMesh.prototype.getIndices = function () {
  12774. return null;
  12775. };
  12776. /**
  12777. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12778. * Returned type : float array or Float32Array
  12779. */
  12780. AbstractMesh.prototype.getVerticesData = function (kind) {
  12781. return null;
  12782. };
  12783. /**
  12784. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12785. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12786. * The `data` are either a numeric array either a Float32Array.
  12787. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12788. * 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).
  12789. * Note that a new underlying VertexBuffer object is created each call.
  12790. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12791. *
  12792. * Possible `kind` values :
  12793. * - BABYLON.VertexBuffer.PositionKind
  12794. * - BABYLON.VertexBuffer.UVKind
  12795. * - BABYLON.VertexBuffer.UV2Kind
  12796. * - BABYLON.VertexBuffer.UV3Kind
  12797. * - BABYLON.VertexBuffer.UV4Kind
  12798. * - BABYLON.VertexBuffer.UV5Kind
  12799. * - BABYLON.VertexBuffer.UV6Kind
  12800. * - BABYLON.VertexBuffer.ColorKind
  12801. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12802. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12803. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12804. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12805. *
  12806. * Returns the Mesh.
  12807. */
  12808. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12809. return null;
  12810. };
  12811. /**
  12812. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12813. * If the mesh has no geometry, it is simply returned as it is.
  12814. * The `data` are either a numeric array either a Float32Array.
  12815. * No new underlying VertexBuffer object is created.
  12816. * 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.
  12817. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12818. *
  12819. * Possible `kind` values :
  12820. * - BABYLON.VertexBuffer.PositionKind
  12821. * - BABYLON.VertexBuffer.UVKind
  12822. * - BABYLON.VertexBuffer.UV2Kind
  12823. * - BABYLON.VertexBuffer.UV3Kind
  12824. * - BABYLON.VertexBuffer.UV4Kind
  12825. * - BABYLON.VertexBuffer.UV5Kind
  12826. * - BABYLON.VertexBuffer.UV6Kind
  12827. * - BABYLON.VertexBuffer.ColorKind
  12828. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12829. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12830. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12831. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12832. *
  12833. * Returns the Mesh.
  12834. */
  12835. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12836. return null;
  12837. };
  12838. /**
  12839. * Sets the mesh indices.
  12840. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12841. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12842. * This method creates a new index buffer each call.
  12843. * Returns the Mesh.
  12844. */
  12845. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12846. return null;
  12847. };
  12848. /** Returns false by default, used by the class Mesh.
  12849. * Returns a boolean
  12850. */
  12851. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12852. return false;
  12853. };
  12854. /**
  12855. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12856. * Returns a BoundingInfo
  12857. */
  12858. AbstractMesh.prototype.getBoundingInfo = function () {
  12859. if (this._masterMesh) {
  12860. return this._masterMesh.getBoundingInfo();
  12861. }
  12862. if (!this._boundingInfo) {
  12863. this._updateBoundingInfo();
  12864. }
  12865. return this._boundingInfo;
  12866. };
  12867. /**
  12868. * Sets a mesh new object BoundingInfo.
  12869. * Returns the AbstractMesh.
  12870. */
  12871. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12872. this._boundingInfo = boundingInfo;
  12873. return this;
  12874. };
  12875. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12876. get: function () {
  12877. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12878. },
  12879. enumerable: true,
  12880. configurable: true
  12881. });
  12882. AbstractMesh.prototype._preActivate = function () {
  12883. };
  12884. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12885. };
  12886. AbstractMesh.prototype._activate = function (renderId) {
  12887. this._renderId = renderId;
  12888. };
  12889. /**
  12890. * Returns the last update of the World matrix
  12891. * Returns a Matrix.
  12892. */
  12893. AbstractMesh.prototype.getWorldMatrix = function () {
  12894. if (this._masterMesh) {
  12895. return this._masterMesh.getWorldMatrix();
  12896. }
  12897. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12898. this.computeWorldMatrix();
  12899. }
  12900. return this._worldMatrix;
  12901. };
  12902. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12903. /**
  12904. * Returns directly the last state of the mesh World matrix.
  12905. * A Matrix is returned.
  12906. */
  12907. get: function () {
  12908. return this._worldMatrix;
  12909. },
  12910. enumerable: true,
  12911. configurable: true
  12912. });
  12913. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12914. /**
  12915. * Returns the current mesh absolute position.
  12916. * Retuns a Vector3.
  12917. */
  12918. get: function () {
  12919. return this._absolutePosition;
  12920. },
  12921. enumerable: true,
  12922. configurable: true
  12923. });
  12924. /**
  12925. * Prevents the World matrix to be computed any longer.
  12926. * Returns the AbstractMesh.
  12927. */
  12928. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12929. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12930. this.computeWorldMatrix(true);
  12931. this._isWorldMatrixFrozen = true;
  12932. return this;
  12933. };
  12934. /**
  12935. * Allows back the World matrix computation.
  12936. * Returns the AbstractMesh.
  12937. */
  12938. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12939. this._isWorldMatrixFrozen = false;
  12940. this.computeWorldMatrix(true);
  12941. return this;
  12942. };
  12943. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12944. /**
  12945. * True if the World matrix has been frozen.
  12946. * Returns a boolean.
  12947. */
  12948. get: function () {
  12949. return this._isWorldMatrixFrozen;
  12950. },
  12951. enumerable: true,
  12952. configurable: true
  12953. });
  12954. /**
  12955. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12956. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12957. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12958. * The passed axis is also normalized.
  12959. * Returns the AbstractMesh.
  12960. */
  12961. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12962. axis.normalize();
  12963. if (!this.rotationQuaternion) {
  12964. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12965. this.rotation = BABYLON.Vector3.Zero();
  12966. }
  12967. var rotationQuaternion;
  12968. if (!space || space === BABYLON.Space.LOCAL) {
  12969. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12970. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12971. }
  12972. else {
  12973. if (this.parent) {
  12974. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12975. invertParentWorldMatrix.invert();
  12976. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12977. }
  12978. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12979. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12980. }
  12981. return this;
  12982. };
  12983. /**
  12984. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12985. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12986. * The passed axis is also normalized.
  12987. * Returns the AbstractMesh.
  12988. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12989. */
  12990. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12991. axis.normalize();
  12992. if (!this.rotationQuaternion) {
  12993. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12994. this.rotation.copyFromFloats(0, 0, 0);
  12995. }
  12996. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12997. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12998. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12999. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13000. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13001. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13002. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13003. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13004. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13005. return this;
  13006. };
  13007. /**
  13008. * Translates the mesh along the axis vector for the passed distance in the given space.
  13009. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13010. * Returns the AbstractMesh.
  13011. */
  13012. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13013. var displacementVector = axis.scale(distance);
  13014. if (!space || space === BABYLON.Space.LOCAL) {
  13015. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13016. this.setPositionWithLocalVector(tempV3);
  13017. }
  13018. else {
  13019. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13020. }
  13021. return this;
  13022. };
  13023. /**
  13024. * Adds a rotation step to the mesh current rotation.
  13025. * x, y, z are Euler angles expressed in radians.
  13026. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13027. * This means this rotation is made in the mesh local space only.
  13028. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13029. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13030. * ```javascript
  13031. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13032. * ```
  13033. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13034. * 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.
  13035. * Returns the AbstractMesh.
  13036. */
  13037. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13038. var rotationQuaternion;
  13039. if (this.rotationQuaternion) {
  13040. rotationQuaternion = this.rotationQuaternion;
  13041. }
  13042. else {
  13043. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13044. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13045. }
  13046. var accumulation = BABYLON.Tmp.Quaternion[0];
  13047. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13048. rotationQuaternion.multiplyInPlace(accumulation);
  13049. if (!this.rotationQuaternion) {
  13050. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13051. }
  13052. return this;
  13053. };
  13054. /**
  13055. * Retuns the mesh absolute position in the World.
  13056. * Returns a Vector3.
  13057. */
  13058. AbstractMesh.prototype.getAbsolutePosition = function () {
  13059. this.computeWorldMatrix();
  13060. return this._absolutePosition;
  13061. };
  13062. /**
  13063. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13064. * Returns the AbstractMesh.
  13065. */
  13066. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13067. if (!absolutePosition) {
  13068. return;
  13069. }
  13070. var absolutePositionX;
  13071. var absolutePositionY;
  13072. var absolutePositionZ;
  13073. if (absolutePosition.x === undefined) {
  13074. if (arguments.length < 3) {
  13075. return;
  13076. }
  13077. absolutePositionX = arguments[0];
  13078. absolutePositionY = arguments[1];
  13079. absolutePositionZ = arguments[2];
  13080. }
  13081. else {
  13082. absolutePositionX = absolutePosition.x;
  13083. absolutePositionY = absolutePosition.y;
  13084. absolutePositionZ = absolutePosition.z;
  13085. }
  13086. if (this.parent) {
  13087. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13088. invertParentWorldMatrix.invert();
  13089. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13090. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13091. }
  13092. else {
  13093. this.position.x = absolutePositionX;
  13094. this.position.y = absolutePositionY;
  13095. this.position.z = absolutePositionZ;
  13096. }
  13097. return this;
  13098. };
  13099. // ================================== Point of View Movement =================================
  13100. /**
  13101. * Perform relative position change from the point of view of behind the front of the mesh.
  13102. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13103. * Supports definition of mesh facing forward or backward.
  13104. * @param {number} amountRight
  13105. * @param {number} amountUp
  13106. * @param {number} amountForward
  13107. *
  13108. * Returns the AbstractMesh.
  13109. */
  13110. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13111. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13112. return this;
  13113. };
  13114. /**
  13115. * Calculate relative position change from the point of view of behind the front of the mesh.
  13116. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13117. * Supports definition of mesh facing forward or backward.
  13118. * @param {number} amountRight
  13119. * @param {number} amountUp
  13120. * @param {number} amountForward
  13121. *
  13122. * Returns a new Vector3.
  13123. */
  13124. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13125. var rotMatrix = new BABYLON.Matrix();
  13126. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13127. rotQuaternion.toRotationMatrix(rotMatrix);
  13128. var translationDelta = BABYLON.Vector3.Zero();
  13129. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13130. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13131. return translationDelta;
  13132. };
  13133. // ================================== Point of View Rotation =================================
  13134. /**
  13135. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13136. * Supports definition of mesh facing forward or backward.
  13137. * @param {number} flipBack
  13138. * @param {number} twirlClockwise
  13139. * @param {number} tiltRight
  13140. *
  13141. * Returns the AbstractMesh.
  13142. */
  13143. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13144. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13145. return this;
  13146. };
  13147. /**
  13148. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13149. * Supports definition of mesh facing forward or backward.
  13150. * @param {number} flipBack
  13151. * @param {number} twirlClockwise
  13152. * @param {number} tiltRight
  13153. *
  13154. * Returns a new Vector3.
  13155. */
  13156. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13157. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13158. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13159. };
  13160. /**
  13161. * Sets a new pivot matrix to the mesh.
  13162. * Returns the AbstractMesh.
  13163. */
  13164. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13165. this._pivotMatrix = matrix;
  13166. this._cache.pivotMatrixUpdated = true;
  13167. return this;
  13168. };
  13169. /**
  13170. * Returns the mesh pivot matrix.
  13171. * Default : Identity.
  13172. * A Matrix is returned.
  13173. */
  13174. AbstractMesh.prototype.getPivotMatrix = function () {
  13175. return this._pivotMatrix;
  13176. };
  13177. AbstractMesh.prototype._isSynchronized = function () {
  13178. if (this._isDirty) {
  13179. return false;
  13180. }
  13181. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13182. return false;
  13183. if (this._cache.pivotMatrixUpdated) {
  13184. return false;
  13185. }
  13186. if (this.infiniteDistance) {
  13187. return false;
  13188. }
  13189. if (!this._cache.position.equals(this.position))
  13190. return false;
  13191. if (this.rotationQuaternion) {
  13192. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13193. return false;
  13194. }
  13195. if (!this._cache.rotation.equals(this.rotation))
  13196. return false;
  13197. if (!this._cache.scaling.equals(this.scaling))
  13198. return false;
  13199. return true;
  13200. };
  13201. AbstractMesh.prototype._initCache = function () {
  13202. _super.prototype._initCache.call(this);
  13203. this._cache.localMatrixUpdated = false;
  13204. this._cache.position = BABYLON.Vector3.Zero();
  13205. this._cache.scaling = BABYLON.Vector3.Zero();
  13206. this._cache.rotation = BABYLON.Vector3.Zero();
  13207. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13208. this._cache.billboardMode = -1;
  13209. };
  13210. AbstractMesh.prototype.markAsDirty = function (property) {
  13211. if (property === "rotation") {
  13212. this.rotationQuaternion = null;
  13213. }
  13214. this._currentRenderId = Number.MAX_VALUE;
  13215. this._isDirty = true;
  13216. return this;
  13217. };
  13218. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13219. this.computeWorldMatrix();
  13220. var min = this.getBoundingInfo().boundingBox.minimumWorld;
  13221. var max = this.getBoundingInfo().boundingBox.maximumWorld;
  13222. var descendants = this.getDescendants(false, function (node) { return node.subMeshes; });
  13223. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13224. var descendant = descendants_1[_i];
  13225. var childMesh = descendant;
  13226. childMesh.computeWorldMatrix();
  13227. var minBox = childMesh.getBoundingInfo().boundingBox.minimumWorld;
  13228. var maxBox = childMesh.getBoundingInfo().boundingBox.maximumWorld;
  13229. BABYLON.Tools.CheckExtends(minBox, min, max);
  13230. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13231. }
  13232. return {
  13233. min: min,
  13234. max: max
  13235. };
  13236. };
  13237. /**
  13238. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13239. * Returns the AbstractMesh.
  13240. */
  13241. AbstractMesh.prototype._updateBoundingInfo = function () {
  13242. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13243. this._boundingInfo.update(this.worldMatrixFromCache);
  13244. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13245. return this;
  13246. };
  13247. /**
  13248. * Update a mesh's children BoundingInfo objects only.
  13249. * Returns the AbstractMesh.
  13250. */
  13251. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13252. if (!this.subMeshes) {
  13253. return;
  13254. }
  13255. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13256. var subMesh = this.subMeshes[subIndex];
  13257. if (!subMesh.IsGlobal) {
  13258. subMesh.updateBoundingInfo(matrix);
  13259. }
  13260. }
  13261. return this;
  13262. };
  13263. /**
  13264. * Computes the mesh World matrix and returns it.
  13265. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13266. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13267. * If the parameter `force`is set to `true`, the actual computation is done.
  13268. * Returns the mesh World Matrix.
  13269. */
  13270. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13271. if (this._isWorldMatrixFrozen) {
  13272. return this._worldMatrix;
  13273. }
  13274. if (!force && this.isSynchronized(true)) {
  13275. this._currentRenderId = this.getScene().getRenderId();
  13276. return this._worldMatrix;
  13277. }
  13278. this._cache.position.copyFrom(this.position);
  13279. this._cache.scaling.copyFrom(this.scaling);
  13280. this._cache.pivotMatrixUpdated = false;
  13281. this._cache.billboardMode = this.billboardMode;
  13282. this._currentRenderId = this.getScene().getRenderId();
  13283. this._isDirty = false;
  13284. // Scaling
  13285. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13286. // Rotation
  13287. //rotate, if quaternion is set and rotation was used
  13288. if (this.rotationQuaternion) {
  13289. var len = this.rotation.length();
  13290. if (len) {
  13291. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13292. this.rotation.copyFromFloats(0, 0, 0);
  13293. }
  13294. }
  13295. if (this.rotationQuaternion) {
  13296. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13297. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13298. }
  13299. else {
  13300. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13301. this._cache.rotation.copyFrom(this.rotation);
  13302. }
  13303. // Translation
  13304. if (this.infiniteDistance && !this.parent) {
  13305. var camera = this.getScene().activeCamera;
  13306. if (camera) {
  13307. var cameraWorldMatrix = camera.getWorldMatrix();
  13308. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13309. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13310. }
  13311. }
  13312. else {
  13313. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13314. }
  13315. // Composing transformations
  13316. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13317. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13318. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13319. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13320. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13321. // Need to decompose each rotation here
  13322. var currentPosition = BABYLON.Tmp.Vector3[3];
  13323. if (this.parent && this.parent.getWorldMatrix) {
  13324. if (this._meshToBoneReferal) {
  13325. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13326. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13327. }
  13328. else {
  13329. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13330. }
  13331. }
  13332. else {
  13333. currentPosition.copyFrom(this.position);
  13334. }
  13335. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13336. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13337. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13338. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13339. }
  13340. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13341. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13342. }
  13343. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13344. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13345. }
  13346. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13347. }
  13348. else {
  13349. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13350. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13351. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13352. }
  13353. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13354. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13355. }
  13356. // Local world
  13357. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13358. // Parent
  13359. if (this.parent && this.parent.getWorldMatrix) {
  13360. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13361. if (this._meshToBoneReferal) {
  13362. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13363. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13364. }
  13365. else {
  13366. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13367. }
  13368. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13369. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13370. this._worldMatrix.copyFrom(this._localWorld);
  13371. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13372. }
  13373. else {
  13374. if (this._meshToBoneReferal) {
  13375. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13376. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13377. }
  13378. else {
  13379. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13380. }
  13381. }
  13382. this._markSyncedWithParent();
  13383. }
  13384. else {
  13385. this._worldMatrix.copyFrom(this._localWorld);
  13386. }
  13387. // Bounding info
  13388. this._updateBoundingInfo();
  13389. // Absolute position
  13390. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13391. // Callbacks
  13392. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13393. if (!this._poseMatrix) {
  13394. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13395. }
  13396. return this._worldMatrix;
  13397. };
  13398. /**
  13399. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13400. * @param func: callback function to add
  13401. *
  13402. * Returns the AbstractMesh.
  13403. */
  13404. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13405. this.onAfterWorldMatrixUpdateObservable.add(func);
  13406. return this;
  13407. };
  13408. /**
  13409. * Removes a registered callback function.
  13410. * Returns the AbstractMesh.
  13411. */
  13412. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13413. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13414. return this;
  13415. };
  13416. /**
  13417. * Sets the mesh position in its local space.
  13418. * Returns the AbstractMesh.
  13419. */
  13420. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13421. this.computeWorldMatrix();
  13422. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13423. return this;
  13424. };
  13425. /**
  13426. * Returns the mesh position in the local space from the current World matrix values.
  13427. * Returns a new Vector3.
  13428. */
  13429. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13430. this.computeWorldMatrix();
  13431. var invLocalWorldMatrix = this._localWorld.clone();
  13432. invLocalWorldMatrix.invert();
  13433. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13434. };
  13435. /**
  13436. * Translates the mesh along the passed Vector3 in its local space.
  13437. * Returns the AbstractMesh.
  13438. */
  13439. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13440. this.computeWorldMatrix(true);
  13441. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13442. return this;
  13443. };
  13444. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13445. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13446. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13447. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13448. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13449. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13450. /// <returns>Mesh oriented towards targetMesh</returns>
  13451. if (yawCor === void 0) { yawCor = 0; }
  13452. if (pitchCor === void 0) { pitchCor = 0; }
  13453. if (rollCor === void 0) { rollCor = 0; }
  13454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13455. var dv = AbstractMesh._lookAtVectorCache;
  13456. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13457. targetPoint.subtractToRef(pos, dv);
  13458. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13459. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13460. var pitch = Math.atan2(dv.y, len);
  13461. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13462. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13463. return this;
  13464. };
  13465. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13466. this._meshToBoneReferal = affectedMesh;
  13467. this.parent = bone;
  13468. if (bone.getWorldMatrix().determinant() < 0) {
  13469. this.scalingDeterminant *= -1;
  13470. }
  13471. return this;
  13472. };
  13473. AbstractMesh.prototype.detachFromBone = function () {
  13474. if (this.parent.getWorldMatrix().determinant() < 0) {
  13475. this.scalingDeterminant *= -1;
  13476. }
  13477. this._meshToBoneReferal = null;
  13478. this.parent = null;
  13479. return this;
  13480. };
  13481. /**
  13482. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13483. * A mesh is in the frustum if its bounding box intersects the frustum.
  13484. * Boolean returned.
  13485. */
  13486. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13487. return this._boundingInfo.isInFrustum(frustumPlanes);
  13488. };
  13489. /**
  13490. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13491. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13492. * Boolean returned.
  13493. */
  13494. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13495. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13496. ;
  13497. };
  13498. /**
  13499. * True if the mesh intersects another mesh or a SolidParticle object.
  13500. * 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)
  13501. * Returns a boolean.
  13502. */
  13503. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13504. if (!this._boundingInfo || !mesh._boundingInfo) {
  13505. return false;
  13506. }
  13507. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13508. };
  13509. /**
  13510. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13511. * Returns a boolean.
  13512. */
  13513. AbstractMesh.prototype.intersectsPoint = function (point) {
  13514. if (!this._boundingInfo) {
  13515. return false;
  13516. }
  13517. return this._boundingInfo.intersectsPoint(point);
  13518. };
  13519. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13520. return this.physicsImpostor;
  13521. };
  13522. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13523. if (!camera) {
  13524. camera = this.getScene().activeCamera;
  13525. }
  13526. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13527. };
  13528. /**
  13529. * Returns the distance from the mesh to the active camera.
  13530. * Returns a float.
  13531. */
  13532. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13533. if (!camera) {
  13534. camera = this.getScene().activeCamera;
  13535. }
  13536. return this.absolutePosition.subtract(camera.position).length();
  13537. };
  13538. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13539. if (!this.physicsImpostor) {
  13540. return;
  13541. }
  13542. this.physicsImpostor.applyImpulse(force, contactPoint);
  13543. return this;
  13544. };
  13545. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13546. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13547. return;
  13548. }
  13549. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13550. mainPivot: pivot1,
  13551. connectedPivot: pivot2,
  13552. nativeParams: options
  13553. });
  13554. return this;
  13555. };
  13556. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13557. // Collisions
  13558. /**
  13559. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13560. * Default `false`.
  13561. */
  13562. get: function () {
  13563. return this._checkCollisions;
  13564. },
  13565. set: function (collisionEnabled) {
  13566. this._checkCollisions = collisionEnabled;
  13567. if (this.getScene().workerCollisions) {
  13568. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13569. }
  13570. },
  13571. enumerable: true,
  13572. configurable: true
  13573. });
  13574. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13575. var globalPosition = this.getAbsolutePosition();
  13576. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13577. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13578. if (!this._collider) {
  13579. this._collider = new BABYLON.Collider();
  13580. }
  13581. this._collider.radius = this.ellipsoid;
  13582. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13583. return this;
  13584. };
  13585. // Submeshes octree
  13586. /**
  13587. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13588. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13589. * Returns an Octree of submeshes.
  13590. */
  13591. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13592. if (maxCapacity === void 0) { maxCapacity = 64; }
  13593. if (maxDepth === void 0) { maxDepth = 2; }
  13594. if (!this._submeshesOctree) {
  13595. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13596. }
  13597. this.computeWorldMatrix(true);
  13598. // Update octree
  13599. var bbox = this.getBoundingInfo().boundingBox;
  13600. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13601. return this._submeshesOctree;
  13602. };
  13603. // Collisions
  13604. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13605. this._generatePointsArray();
  13606. // Transformation
  13607. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13608. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13609. subMesh._lastColliderWorldVertices = [];
  13610. subMesh._trianglePlanes = [];
  13611. var start = subMesh.verticesStart;
  13612. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13613. for (var i = start; i < end; i++) {
  13614. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13615. }
  13616. }
  13617. // Collide
  13618. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13619. if (collider.collisionFound) {
  13620. collider.collidedMesh = this;
  13621. }
  13622. return this;
  13623. };
  13624. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13625. var subMeshes;
  13626. var len;
  13627. // Octrees
  13628. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13629. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13630. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13631. len = intersections.length;
  13632. subMeshes = intersections.data;
  13633. }
  13634. else {
  13635. subMeshes = this.subMeshes;
  13636. len = subMeshes.length;
  13637. }
  13638. for (var index = 0; index < len; index++) {
  13639. var subMesh = subMeshes[index];
  13640. // Bounding test
  13641. if (len > 1 && !subMesh._checkCollision(collider))
  13642. continue;
  13643. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13644. }
  13645. return this;
  13646. };
  13647. AbstractMesh.prototype._checkCollision = function (collider) {
  13648. // Bounding box test
  13649. if (!this._boundingInfo._checkCollision(collider))
  13650. return this;
  13651. // Transformation matrix
  13652. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13653. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13654. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13655. return this;
  13656. };
  13657. // Picking
  13658. AbstractMesh.prototype._generatePointsArray = function () {
  13659. return false;
  13660. };
  13661. /**
  13662. * Checks if the passed Ray intersects with the mesh.
  13663. * Returns an object PickingInfo.
  13664. */
  13665. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13666. var pickingInfo = new BABYLON.PickingInfo();
  13667. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13668. return pickingInfo;
  13669. }
  13670. if (!this._generatePointsArray()) {
  13671. return pickingInfo;
  13672. }
  13673. var intersectInfo = null;
  13674. // Octrees
  13675. var subMeshes;
  13676. var len;
  13677. if (this._submeshesOctree && this.useOctreeForPicking) {
  13678. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13679. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13680. len = intersections.length;
  13681. subMeshes = intersections.data;
  13682. }
  13683. else {
  13684. subMeshes = this.subMeshes;
  13685. len = subMeshes.length;
  13686. }
  13687. for (var index = 0; index < len; index++) {
  13688. var subMesh = subMeshes[index];
  13689. // Bounding test
  13690. if (len > 1 && !subMesh.canIntersects(ray))
  13691. continue;
  13692. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13693. if (currentIntersectInfo) {
  13694. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13695. intersectInfo = currentIntersectInfo;
  13696. intersectInfo.subMeshId = index;
  13697. if (fastCheck) {
  13698. break;
  13699. }
  13700. }
  13701. }
  13702. }
  13703. if (intersectInfo) {
  13704. // Get picked point
  13705. var world = this.getWorldMatrix();
  13706. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13707. var direction = ray.direction.clone();
  13708. direction = direction.scale(intersectInfo.distance);
  13709. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13710. var pickedPoint = worldOrigin.add(worldDirection);
  13711. // Return result
  13712. pickingInfo.hit = true;
  13713. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13714. pickingInfo.pickedPoint = pickedPoint;
  13715. pickingInfo.pickedMesh = this;
  13716. pickingInfo.bu = intersectInfo.bu;
  13717. pickingInfo.bv = intersectInfo.bv;
  13718. pickingInfo.faceId = intersectInfo.faceId;
  13719. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13720. return pickingInfo;
  13721. }
  13722. return pickingInfo;
  13723. };
  13724. /**
  13725. * Clones the mesh, used by the class Mesh.
  13726. * Just returns `null` for an AbstractMesh.
  13727. */
  13728. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13729. return null;
  13730. };
  13731. /**
  13732. * Disposes all the mesh submeshes.
  13733. * Returns the AbstractMesh.
  13734. */
  13735. AbstractMesh.prototype.releaseSubMeshes = function () {
  13736. if (this.subMeshes) {
  13737. while (this.subMeshes.length) {
  13738. this.subMeshes[0].dispose();
  13739. }
  13740. }
  13741. else {
  13742. this.subMeshes = new Array();
  13743. }
  13744. return this;
  13745. };
  13746. /**
  13747. * Disposes the AbstractMesh.
  13748. * Some internal references are kept for further use.
  13749. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13750. * Returns nothing.
  13751. */
  13752. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13753. var _this = this;
  13754. var index;
  13755. // Action manager
  13756. if (this.actionManager) {
  13757. this.actionManager.dispose();
  13758. this.actionManager = null;
  13759. }
  13760. // Skeleton
  13761. this.skeleton = null;
  13762. // Animations
  13763. this.getScene().stopAnimation(this);
  13764. // Physics
  13765. if (this.physicsImpostor) {
  13766. this.physicsImpostor.dispose();
  13767. }
  13768. // Intersections in progress
  13769. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13770. var other = this._intersectionsInProgress[index];
  13771. var pos = other._intersectionsInProgress.indexOf(this);
  13772. other._intersectionsInProgress.splice(pos, 1);
  13773. }
  13774. this._intersectionsInProgress = [];
  13775. // Lights
  13776. var lights = this.getScene().lights;
  13777. lights.forEach(function (light) {
  13778. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13779. if (meshIndex !== -1) {
  13780. light.includedOnlyMeshes.splice(meshIndex, 1);
  13781. }
  13782. meshIndex = light.excludedMeshes.indexOf(_this);
  13783. if (meshIndex !== -1) {
  13784. light.excludedMeshes.splice(meshIndex, 1);
  13785. }
  13786. // Shadow generators
  13787. var generator = light.getShadowGenerator();
  13788. if (generator) {
  13789. var shadowMap = generator.getShadowMap();
  13790. meshIndex = shadowMap.renderList.indexOf(_this);
  13791. if (meshIndex !== -1) {
  13792. shadowMap.renderList.splice(meshIndex, 1);
  13793. }
  13794. }
  13795. });
  13796. // Edges
  13797. if (this._edgesRenderer) {
  13798. this._edgesRenderer.dispose();
  13799. this._edgesRenderer = null;
  13800. }
  13801. // SubMeshes
  13802. if (this.getClassName() !== "InstancedMesh") {
  13803. this.releaseSubMeshes();
  13804. }
  13805. // Octree
  13806. var sceneOctree = this.getScene().selectionOctree;
  13807. if (sceneOctree) {
  13808. var index = sceneOctree.dynamicContent.indexOf(this);
  13809. if (index !== -1) {
  13810. sceneOctree.dynamicContent.splice(index, 1);
  13811. }
  13812. }
  13813. // Query
  13814. var engine = this.getScene().getEngine();
  13815. if (this._occlusionQuery) {
  13816. this._isOcclusionQueryInProgress = false;
  13817. engine.deleteQuery(this._occlusionQuery);
  13818. this._occlusionQuery = null;
  13819. }
  13820. // Engine
  13821. engine.wipeCaches();
  13822. // Remove from scene
  13823. this.getScene().removeMesh(this);
  13824. if (!doNotRecurse) {
  13825. // Particles
  13826. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13827. if (this.getScene().particleSystems[index].emitter === this) {
  13828. this.getScene().particleSystems[index].dispose();
  13829. index--;
  13830. }
  13831. }
  13832. // Children
  13833. var objects = this.getDescendants(true);
  13834. for (index = 0; index < objects.length; index++) {
  13835. objects[index].dispose();
  13836. }
  13837. }
  13838. else {
  13839. var childMeshes = this.getChildMeshes(true);
  13840. for (index = 0; index < childMeshes.length; index++) {
  13841. var child = childMeshes[index];
  13842. child.parent = null;
  13843. child.computeWorldMatrix(true);
  13844. }
  13845. }
  13846. // facet data
  13847. if (this._facetDataEnabled) {
  13848. this.disableFacetData();
  13849. }
  13850. this.onAfterWorldMatrixUpdateObservable.clear();
  13851. this.onCollideObservable.clear();
  13852. this.onCollisionPositionChangeObservable.clear();
  13853. this._isDisposed = true;
  13854. _super.prototype.dispose.call(this);
  13855. };
  13856. /**
  13857. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13858. * This Vector3 is expressed in the World space.
  13859. */
  13860. AbstractMesh.prototype.getDirection = function (localAxis) {
  13861. var result = BABYLON.Vector3.Zero();
  13862. this.getDirectionToRef(localAxis, result);
  13863. return result;
  13864. };
  13865. /**
  13866. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13867. * localAxis is expressed in the mesh local space.
  13868. * result is computed in the Wordl space from the mesh World matrix.
  13869. * Returns the AbstractMesh.
  13870. */
  13871. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13872. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13873. return this;
  13874. };
  13875. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13876. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13877. if (this.getScene().getRenderId() == 0) {
  13878. this.computeWorldMatrix(true);
  13879. }
  13880. var wm = this.getWorldMatrix();
  13881. if (space == BABYLON.Space.WORLD) {
  13882. var tmat = BABYLON.Tmp.Matrix[0];
  13883. wm.invertToRef(tmat);
  13884. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13885. }
  13886. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13887. this._pivotMatrix.m[12] = -point.x;
  13888. this._pivotMatrix.m[13] = -point.y;
  13889. this._pivotMatrix.m[14] = -point.z;
  13890. this._cache.pivotMatrixUpdated = true;
  13891. return this;
  13892. };
  13893. /**
  13894. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13895. */
  13896. AbstractMesh.prototype.getPivotPoint = function () {
  13897. var point = BABYLON.Vector3.Zero();
  13898. this.getPivotPointToRef(point);
  13899. return point;
  13900. };
  13901. /**
  13902. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13903. * Returns the AbstractMesh.
  13904. */
  13905. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13906. result.x = -this._pivotMatrix.m[12];
  13907. result.y = -this._pivotMatrix.m[13];
  13908. result.z = -this._pivotMatrix.m[14];
  13909. return this;
  13910. };
  13911. /**
  13912. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13913. */
  13914. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13915. var point = BABYLON.Vector3.Zero();
  13916. this.getAbsolutePivotPointToRef(point);
  13917. return point;
  13918. };
  13919. /**
  13920. * Defines the passed mesh as the parent of the current mesh.
  13921. * Returns the AbstractMesh.
  13922. */
  13923. AbstractMesh.prototype.setParent = function (mesh) {
  13924. var child = this;
  13925. var parent = mesh;
  13926. if (mesh == null) {
  13927. var rotation = BABYLON.Tmp.Quaternion[0];
  13928. var position = BABYLON.Tmp.Vector3[0];
  13929. var scale = BABYLON.Tmp.Vector3[1];
  13930. child.getWorldMatrix().decompose(scale, rotation, position);
  13931. if (child.rotationQuaternion) {
  13932. child.rotationQuaternion.copyFrom(rotation);
  13933. }
  13934. else {
  13935. rotation.toEulerAnglesToRef(child.rotation);
  13936. }
  13937. child.position.x = position.x;
  13938. child.position.y = position.y;
  13939. child.position.z = position.z;
  13940. }
  13941. else {
  13942. var position = BABYLON.Tmp.Vector3[0];
  13943. var m1 = BABYLON.Tmp.Matrix[0];
  13944. parent.getWorldMatrix().invertToRef(m1);
  13945. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  13946. child.position.copyFrom(position);
  13947. }
  13948. child.parent = parent;
  13949. return this;
  13950. };
  13951. /**
  13952. * Adds the passed mesh as a child to the current mesh.
  13953. * Returns the AbstractMesh.
  13954. */
  13955. AbstractMesh.prototype.addChild = function (mesh) {
  13956. mesh.setParent(this);
  13957. return this;
  13958. };
  13959. /**
  13960. * Removes the passed mesh from the current mesh children list.
  13961. * Returns the AbstractMesh.
  13962. */
  13963. AbstractMesh.prototype.removeChild = function (mesh) {
  13964. mesh.setParent(null);
  13965. return this;
  13966. };
  13967. /**
  13968. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13969. * Returns the AbstractMesh.
  13970. */
  13971. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13972. result.x = this._pivotMatrix.m[12];
  13973. result.y = this._pivotMatrix.m[13];
  13974. result.z = this._pivotMatrix.m[14];
  13975. this.getPivotPointToRef(result);
  13976. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13977. return this;
  13978. };
  13979. // Facet data
  13980. /**
  13981. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13982. * Returns the AbstractMesh.
  13983. */
  13984. AbstractMesh.prototype._initFacetData = function () {
  13985. if (!this._facetNormals) {
  13986. this._facetNormals = new Array();
  13987. }
  13988. if (!this._facetPositions) {
  13989. this._facetPositions = new Array();
  13990. }
  13991. if (!this._facetPartitioning) {
  13992. this._facetPartitioning = new Array();
  13993. }
  13994. this._facetNb = this.getIndices().length / 3;
  13995. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13996. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13997. for (var f = 0; f < this._facetNb; f++) {
  13998. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13999. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14000. }
  14001. this._facetDataEnabled = true;
  14002. return this;
  14003. };
  14004. /**
  14005. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14006. * This method can be called within the render loop.
  14007. * 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.
  14008. * Returns the AbstractMesh.
  14009. */
  14010. AbstractMesh.prototype.updateFacetData = function () {
  14011. if (!this._facetDataEnabled) {
  14012. this._initFacetData();
  14013. }
  14014. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14015. var indices = this.getIndices();
  14016. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14017. var bInfo = this.getBoundingInfo();
  14018. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14019. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14020. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14021. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14022. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14023. this._subDiv.max = this._partitioningSubdivisions;
  14024. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14025. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14026. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14027. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14028. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14029. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14030. // set the parameters for ComputeNormals()
  14031. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14032. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14033. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14034. this._facetParameters.bInfo = bInfo;
  14035. this._facetParameters.bbSize = this._bbSize;
  14036. this._facetParameters.subDiv = this._subDiv;
  14037. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14038. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14039. return this;
  14040. };
  14041. /**
  14042. * Returns the facetLocalNormals array.
  14043. * The normals are expressed in the mesh local space.
  14044. */
  14045. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14046. if (!this._facetNormals) {
  14047. this.updateFacetData();
  14048. }
  14049. return this._facetNormals;
  14050. };
  14051. /**
  14052. * Returns the facetLocalPositions array.
  14053. * The facet positions are expressed in the mesh local space.
  14054. */
  14055. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14056. if (!this._facetPositions) {
  14057. this.updateFacetData();
  14058. }
  14059. return this._facetPositions;
  14060. };
  14061. /**
  14062. * Returns the facetLocalPartioning array.
  14063. */
  14064. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14065. if (!this._facetPartitioning) {
  14066. this.updateFacetData();
  14067. }
  14068. return this._facetPartitioning;
  14069. };
  14070. /**
  14071. * Returns the i-th facet position in the world system.
  14072. * This method allocates a new Vector3 per call.
  14073. */
  14074. AbstractMesh.prototype.getFacetPosition = function (i) {
  14075. var pos = BABYLON.Vector3.Zero();
  14076. this.getFacetPositionToRef(i, pos);
  14077. return pos;
  14078. };
  14079. /**
  14080. * Sets the reference Vector3 with the i-th facet position in the world system.
  14081. * Returns the AbstractMesh.
  14082. */
  14083. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14084. var localPos = (this.getFacetLocalPositions())[i];
  14085. var world = this.getWorldMatrix();
  14086. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14087. return this;
  14088. };
  14089. /**
  14090. * Returns the i-th facet normal in the world system.
  14091. * This method allocates a new Vector3 per call.
  14092. */
  14093. AbstractMesh.prototype.getFacetNormal = function (i) {
  14094. var norm = BABYLON.Vector3.Zero();
  14095. this.getFacetNormalToRef(i, norm);
  14096. return norm;
  14097. };
  14098. /**
  14099. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14100. * Returns the AbstractMesh.
  14101. */
  14102. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14103. var localNorm = (this.getFacetLocalNormals())[i];
  14104. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14105. return this;
  14106. };
  14107. /**
  14108. * 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).
  14109. */
  14110. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14111. var bInfo = this.getBoundingInfo();
  14112. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14113. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14114. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14115. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14116. return null;
  14117. }
  14118. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14119. };
  14120. /**
  14121. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14122. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14123. * 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.
  14124. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14125. * 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.
  14126. */
  14127. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14128. if (checkFace === void 0) { checkFace = false; }
  14129. if (facing === void 0) { facing = true; }
  14130. var world = this.getWorldMatrix();
  14131. var invMat = BABYLON.Tmp.Matrix[5];
  14132. world.invertToRef(invMat);
  14133. var invVect = BABYLON.Tmp.Vector3[8];
  14134. var closest = null;
  14135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14136. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14137. if (projected) {
  14138. // tranform the local computed projected vector to world coordinates
  14139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14140. }
  14141. return closest;
  14142. };
  14143. /**
  14144. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14145. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14146. * 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.
  14147. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14148. * 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.
  14149. */
  14150. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14151. if (checkFace === void 0) { checkFace = false; }
  14152. if (facing === void 0) { facing = true; }
  14153. var closest = null;
  14154. var tmpx = 0.0;
  14155. var tmpy = 0.0;
  14156. var tmpz = 0.0;
  14157. var d = 0.0; // tmp dot facet normal * facet position
  14158. var t0 = 0.0;
  14159. var projx = 0.0;
  14160. var projy = 0.0;
  14161. var projz = 0.0;
  14162. // Get all the facets in the same partitioning block than (x, y, z)
  14163. var facetPositions = this.getFacetLocalPositions();
  14164. var facetNormals = this.getFacetLocalNormals();
  14165. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14166. if (!facetsInBlock) {
  14167. return null;
  14168. }
  14169. // Get the closest facet to (x, y, z)
  14170. var shortest = Number.MAX_VALUE; // init distance vars
  14171. var tmpDistance = shortest;
  14172. var fib; // current facet in the block
  14173. var norm; // current facet normal
  14174. var p0; // current facet barycenter position
  14175. // loop on all the facets in the current partitioning block
  14176. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14177. fib = facetsInBlock[idx];
  14178. norm = facetNormals[fib];
  14179. p0 = facetPositions[fib];
  14180. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14181. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14182. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14183. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14184. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14185. projx = x + norm.x * t0;
  14186. projy = y + norm.y * t0;
  14187. projz = z + norm.z * t0;
  14188. tmpx = projx - x;
  14189. tmpy = projy - y;
  14190. tmpz = projz - z;
  14191. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14192. if (tmpDistance < shortest) {
  14193. shortest = tmpDistance;
  14194. closest = fib;
  14195. if (projected) {
  14196. projected.x = projx;
  14197. projected.y = projy;
  14198. projected.z = projz;
  14199. }
  14200. }
  14201. }
  14202. }
  14203. return closest;
  14204. };
  14205. /**
  14206. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14207. */
  14208. AbstractMesh.prototype.getFacetDataParameters = function () {
  14209. return this._facetParameters;
  14210. };
  14211. /**
  14212. * Disables the feature FacetData and frees the related memory.
  14213. * Returns the AbstractMesh.
  14214. */
  14215. AbstractMesh.prototype.disableFacetData = function () {
  14216. if (this._facetDataEnabled) {
  14217. this._facetDataEnabled = false;
  14218. this._facetPositions = null;
  14219. this._facetNormals = null;
  14220. this._facetPartitioning = null;
  14221. this._facetParameters = null;
  14222. }
  14223. return this;
  14224. };
  14225. /**
  14226. * Creates new normals data for the mesh.
  14227. * @param updatable.
  14228. */
  14229. AbstractMesh.prototype.createNormals = function (updatable) {
  14230. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14231. var indices = this.getIndices();
  14232. var normals;
  14233. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14234. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14235. }
  14236. else {
  14237. normals = [];
  14238. }
  14239. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14240. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14241. };
  14242. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14243. var engine = this.getEngine();
  14244. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14245. this._isOccluded = false;
  14246. return;
  14247. }
  14248. if (this.isOcclusionQueryInProgress) {
  14249. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14250. if (isOcclusionQueryAvailable) {
  14251. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14252. this._isOcclusionQueryInProgress = false;
  14253. this._occlusionInternalRetryCounter = 0;
  14254. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14255. }
  14256. else {
  14257. this._occlusionInternalRetryCounter++;
  14258. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14259. this._isOcclusionQueryInProgress = false;
  14260. this._occlusionInternalRetryCounter = 0;
  14261. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14262. // if strict continue the last state of the object.
  14263. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14264. }
  14265. else {
  14266. return;
  14267. }
  14268. }
  14269. }
  14270. var scene = this.getScene();
  14271. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14272. if (!this._occlusionQuery) {
  14273. this._occlusionQuery = engine.createQuery();
  14274. }
  14275. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14276. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14277. engine.endQuery(this.occlusionQueryAlgorithmType);
  14278. this._isOcclusionQueryInProgress = true;
  14279. };
  14280. // Statics
  14281. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14282. AbstractMesh._BILLBOARDMODE_X = 1;
  14283. AbstractMesh._BILLBOARDMODE_Y = 2;
  14284. AbstractMesh._BILLBOARDMODE_Z = 4;
  14285. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14286. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14287. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14288. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14289. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14290. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14291. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14292. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14293. return AbstractMesh;
  14294. }(BABYLON.Node));
  14295. BABYLON.AbstractMesh = AbstractMesh;
  14296. })(BABYLON || (BABYLON = {}));
  14297. //# sourceMappingURL=babylon.abstractMesh.js.map
  14298. var BABYLON;
  14299. (function (BABYLON) {
  14300. var Light = (function (_super) {
  14301. __extends(Light, _super);
  14302. /**
  14303. * Creates a Light object in the scene.
  14304. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14305. */
  14306. function Light(name, scene) {
  14307. var _this = _super.call(this, name, scene) || this;
  14308. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14309. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14310. _this.intensity = 1.0;
  14311. _this.range = Number.MAX_VALUE;
  14312. /**
  14313. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14314. * of light.
  14315. */
  14316. _this._photometricScale = 1.0;
  14317. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14318. _this._radius = 0.00001;
  14319. _this.renderPriority = 0;
  14320. /**
  14321. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14322. * the current shadow generator.
  14323. */
  14324. _this.shadowEnabled = true;
  14325. _this._excludeWithLayerMask = 0;
  14326. _this._includeOnlyWithLayerMask = 0;
  14327. _this._lightmapMode = 0;
  14328. _this._excludedMeshesIds = new Array();
  14329. _this._includedOnlyMeshesIds = new Array();
  14330. _this.getScene().addLight(_this);
  14331. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14332. _this._buildUniformLayout();
  14333. _this.includedOnlyMeshes = new Array();
  14334. _this.excludedMeshes = new Array();
  14335. _this._resyncMeshes();
  14336. return _this;
  14337. }
  14338. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14339. /**
  14340. * If every light affecting the material is in this lightmapMode,
  14341. * material.lightmapTexture adds or multiplies
  14342. * (depends on material.useLightmapAsShadowmap)
  14343. * after every other light calculations.
  14344. */
  14345. get: function () {
  14346. return Light._LIGHTMAP_DEFAULT;
  14347. },
  14348. enumerable: true,
  14349. configurable: true
  14350. });
  14351. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14352. /**
  14353. * material.lightmapTexture as only diffuse lighting from this light
  14354. * adds pnly specular lighting from this light
  14355. * adds dynamic shadows
  14356. */
  14357. get: function () {
  14358. return Light._LIGHTMAP_SPECULAR;
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14364. /**
  14365. * material.lightmapTexture as only lighting
  14366. * no light calculation from this light
  14367. * only adds dynamic shadows from this light
  14368. */
  14369. get: function () {
  14370. return Light._LIGHTMAP_SHADOWSONLY;
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14376. /**
  14377. * Each light type uses the default quantity according to its type:
  14378. * point/spot lights use luminous intensity
  14379. * directional lights use illuminance
  14380. */
  14381. get: function () {
  14382. return Light._INTENSITYMODE_AUTOMATIC;
  14383. },
  14384. enumerable: true,
  14385. configurable: true
  14386. });
  14387. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14388. /**
  14389. * lumen (lm)
  14390. */
  14391. get: function () {
  14392. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14393. },
  14394. enumerable: true,
  14395. configurable: true
  14396. });
  14397. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14398. /**
  14399. * candela (lm/sr)
  14400. */
  14401. get: function () {
  14402. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14403. },
  14404. enumerable: true,
  14405. configurable: true
  14406. });
  14407. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14408. /**
  14409. * lux (lm/m^2)
  14410. */
  14411. get: function () {
  14412. return Light._INTENSITYMODE_ILLUMINANCE;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14418. /**
  14419. * nit (cd/m^2)
  14420. */
  14421. get: function () {
  14422. return Light._INTENSITYMODE_LUMINANCE;
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14428. /**
  14429. * Light type const id of the point light.
  14430. */
  14431. get: function () {
  14432. return Light._LIGHTTYPEID_POINTLIGHT;
  14433. },
  14434. enumerable: true,
  14435. configurable: true
  14436. });
  14437. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14438. /**
  14439. * Light type const id of the directional light.
  14440. */
  14441. get: function () {
  14442. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14448. /**
  14449. * Light type const id of the spot light.
  14450. */
  14451. get: function () {
  14452. return Light._LIGHTTYPEID_SPOTLIGHT;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14458. /**
  14459. * Light type const id of the hemispheric light.
  14460. */
  14461. get: function () {
  14462. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14463. },
  14464. enumerable: true,
  14465. configurable: true
  14466. });
  14467. Object.defineProperty(Light.prototype, "intensityMode", {
  14468. /**
  14469. * Gets the photometric scale used to interpret the intensity.
  14470. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14471. */
  14472. get: function () {
  14473. return this._intensityMode;
  14474. },
  14475. /**
  14476. * Sets the photometric scale used to interpret the intensity.
  14477. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14478. */
  14479. set: function (value) {
  14480. this._intensityMode = value;
  14481. this._computePhotometricScale();
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. ;
  14487. ;
  14488. Object.defineProperty(Light.prototype, "radius", {
  14489. /**
  14490. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14491. */
  14492. get: function () {
  14493. return this._radius;
  14494. },
  14495. /**
  14496. * sets the light radius used by PBR Materials to simulate soft area lights.
  14497. */
  14498. set: function (value) {
  14499. this._radius = value;
  14500. this._computePhotometricScale();
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. ;
  14506. ;
  14507. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14508. get: function () {
  14509. return this._includedOnlyMeshes;
  14510. },
  14511. set: function (value) {
  14512. this._includedOnlyMeshes = value;
  14513. this._hookArrayForIncludedOnly(value);
  14514. },
  14515. enumerable: true,
  14516. configurable: true
  14517. });
  14518. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14519. get: function () {
  14520. return this._excludedMeshes;
  14521. },
  14522. set: function (value) {
  14523. this._excludedMeshes = value;
  14524. this._hookArrayForExcluded(value);
  14525. },
  14526. enumerable: true,
  14527. configurable: true
  14528. });
  14529. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14530. get: function () {
  14531. return this._excludeWithLayerMask;
  14532. },
  14533. set: function (value) {
  14534. this._excludeWithLayerMask = value;
  14535. this._resyncMeshes();
  14536. },
  14537. enumerable: true,
  14538. configurable: true
  14539. });
  14540. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14541. get: function () {
  14542. return this._includeOnlyWithLayerMask;
  14543. },
  14544. set: function (value) {
  14545. this._includeOnlyWithLayerMask = value;
  14546. this._resyncMeshes();
  14547. },
  14548. enumerable: true,
  14549. configurable: true
  14550. });
  14551. Object.defineProperty(Light.prototype, "lightmapMode", {
  14552. get: function () {
  14553. return this._lightmapMode;
  14554. },
  14555. set: function (value) {
  14556. if (this._lightmapMode === value) {
  14557. return;
  14558. }
  14559. this._lightmapMode = value;
  14560. this._markMeshesAsLightDirty();
  14561. },
  14562. enumerable: true,
  14563. configurable: true
  14564. });
  14565. Light.prototype._buildUniformLayout = function () {
  14566. // Overridden
  14567. };
  14568. /**
  14569. * Returns the string "Light".
  14570. */
  14571. Light.prototype.getClassName = function () {
  14572. return "Light";
  14573. };
  14574. /**
  14575. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14576. */
  14577. Light.prototype.toString = function (fullDetails) {
  14578. var ret = "Name: " + this.name;
  14579. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14580. if (this.animations) {
  14581. for (var i = 0; i < this.animations.length; i++) {
  14582. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14583. }
  14584. }
  14585. if (fullDetails) {
  14586. }
  14587. return ret;
  14588. };
  14589. /**
  14590. * Set the enabled state of this node.
  14591. * @param {boolean} value - the new enabled state
  14592. * @see isEnabled
  14593. */
  14594. Light.prototype.setEnabled = function (value) {
  14595. _super.prototype.setEnabled.call(this, value);
  14596. this._resyncMeshes();
  14597. };
  14598. /**
  14599. * Returns the Light associated shadow generator.
  14600. */
  14601. Light.prototype.getShadowGenerator = function () {
  14602. return this._shadowGenerator;
  14603. };
  14604. /**
  14605. * Returns a Vector3, the absolute light position in the World.
  14606. */
  14607. Light.prototype.getAbsolutePosition = function () {
  14608. return BABYLON.Vector3.Zero();
  14609. };
  14610. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14611. };
  14612. Light.prototype._getWorldMatrix = function () {
  14613. return BABYLON.Matrix.Identity();
  14614. };
  14615. /**
  14616. * Boolean : True if the light will affect the passed mesh.
  14617. */
  14618. Light.prototype.canAffectMesh = function (mesh) {
  14619. if (!mesh) {
  14620. return true;
  14621. }
  14622. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14623. return false;
  14624. }
  14625. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14626. return false;
  14627. }
  14628. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14629. return false;
  14630. }
  14631. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14632. return false;
  14633. }
  14634. return true;
  14635. };
  14636. /**
  14637. * Returns the light World matrix.
  14638. */
  14639. Light.prototype.getWorldMatrix = function () {
  14640. this._currentRenderId = this.getScene().getRenderId();
  14641. var worldMatrix = this._getWorldMatrix();
  14642. if (this.parent && this.parent.getWorldMatrix) {
  14643. if (!this._parentedWorldMatrix) {
  14644. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14645. }
  14646. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14647. this._markSyncedWithParent();
  14648. return this._parentedWorldMatrix;
  14649. }
  14650. return worldMatrix;
  14651. };
  14652. /**
  14653. * Sort function to order lights for rendering.
  14654. * @param a First Light object to compare to second.
  14655. * @param b Second Light object to compare first.
  14656. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14657. */
  14658. Light.compareLightsPriority = function (a, b) {
  14659. //shadow-casting lights have priority over non-shadow-casting lights
  14660. //the renderPrioirty is a secondary sort criterion
  14661. if (a.shadowEnabled !== b.shadowEnabled) {
  14662. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14663. }
  14664. return b.renderPriority - a.renderPriority;
  14665. };
  14666. /**
  14667. * Disposes the light.
  14668. */
  14669. Light.prototype.dispose = function () {
  14670. if (this._shadowGenerator) {
  14671. this._shadowGenerator.dispose();
  14672. this._shadowGenerator = null;
  14673. }
  14674. // Animations
  14675. this.getScene().stopAnimation(this);
  14676. // Remove from meshes
  14677. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14678. var mesh = _a[_i];
  14679. mesh._removeLightSource(this);
  14680. }
  14681. this._uniformBuffer.dispose();
  14682. // Remove from scene
  14683. this.getScene().removeLight(this);
  14684. _super.prototype.dispose.call(this);
  14685. };
  14686. /**
  14687. * Returns the light type ID (integer).
  14688. */
  14689. Light.prototype.getTypeID = function () {
  14690. return 0;
  14691. };
  14692. /**
  14693. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14694. */
  14695. Light.prototype.getScaledIntensity = function () {
  14696. return this._photometricScale * this.intensity;
  14697. };
  14698. /**
  14699. * Returns a new Light object, named "name", from the current one.
  14700. */
  14701. Light.prototype.clone = function (name) {
  14702. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14703. };
  14704. /**
  14705. * Serializes the current light into a Serialization object.
  14706. * Returns the serialized object.
  14707. */
  14708. Light.prototype.serialize = function () {
  14709. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14710. // Type
  14711. serializationObject.type = this.getTypeID();
  14712. // Parent
  14713. if (this.parent) {
  14714. serializationObject.parentId = this.parent.id;
  14715. }
  14716. // Inclusion / exclusions
  14717. if (this.excludedMeshes.length > 0) {
  14718. serializationObject.excludedMeshesIds = [];
  14719. this.excludedMeshes.forEach(function (mesh) {
  14720. serializationObject.excludedMeshesIds.push(mesh.id);
  14721. });
  14722. }
  14723. if (this.includedOnlyMeshes.length > 0) {
  14724. serializationObject.includedOnlyMeshesIds = [];
  14725. this.includedOnlyMeshes.forEach(function (mesh) {
  14726. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14727. });
  14728. }
  14729. // Animations
  14730. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14731. serializationObject.ranges = this.serializeAnimationRanges();
  14732. return serializationObject;
  14733. };
  14734. /**
  14735. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14736. * This new light is named "name" and added to the passed scene.
  14737. */
  14738. Light.GetConstructorFromName = function (type, name, scene) {
  14739. switch (type) {
  14740. case 0:
  14741. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14742. case 1:
  14743. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14744. case 2:
  14745. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14746. case 3:
  14747. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14748. }
  14749. };
  14750. /**
  14751. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14752. */
  14753. Light.Parse = function (parsedLight, scene) {
  14754. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14755. // Inclusion / exclusions
  14756. if (parsedLight.excludedMeshesIds) {
  14757. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14758. }
  14759. if (parsedLight.includedOnlyMeshesIds) {
  14760. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14761. }
  14762. // Parent
  14763. if (parsedLight.parentId) {
  14764. light._waitingParentId = parsedLight.parentId;
  14765. }
  14766. // Animations
  14767. if (parsedLight.animations) {
  14768. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14769. var parsedAnimation = parsedLight.animations[animationIndex];
  14770. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14771. }
  14772. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14773. }
  14774. if (parsedLight.autoAnimate) {
  14775. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14776. }
  14777. return light;
  14778. };
  14779. Light.prototype._hookArrayForExcluded = function (array) {
  14780. var _this = this;
  14781. var oldPush = array.push;
  14782. array.push = function () {
  14783. var items = [];
  14784. for (var _i = 0; _i < arguments.length; _i++) {
  14785. items[_i] = arguments[_i];
  14786. }
  14787. var result = oldPush.apply(array, items);
  14788. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14789. var item = items_1[_a];
  14790. item._resyncLighSource(_this);
  14791. }
  14792. return result;
  14793. };
  14794. var oldSplice = array.splice;
  14795. array.splice = function (index, deleteCount) {
  14796. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14797. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14798. var item = deleted_1[_i];
  14799. item._resyncLighSource(_this);
  14800. }
  14801. return deleted;
  14802. };
  14803. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14804. var item = array_1[_i];
  14805. item._resyncLighSource(this);
  14806. }
  14807. };
  14808. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14809. var _this = this;
  14810. var oldPush = array.push;
  14811. array.push = function () {
  14812. var items = [];
  14813. for (var _i = 0; _i < arguments.length; _i++) {
  14814. items[_i] = arguments[_i];
  14815. }
  14816. var result = oldPush.apply(array, items);
  14817. _this._resyncMeshes();
  14818. return result;
  14819. };
  14820. var oldSplice = array.splice;
  14821. array.splice = function (index, deleteCount) {
  14822. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14823. _this._resyncMeshes();
  14824. return deleted;
  14825. };
  14826. this._resyncMeshes();
  14827. };
  14828. Light.prototype._resyncMeshes = function () {
  14829. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14830. var mesh = _a[_i];
  14831. mesh._resyncLighSource(this);
  14832. }
  14833. };
  14834. Light.prototype._markMeshesAsLightDirty = function () {
  14835. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14836. var mesh = _a[_i];
  14837. if (mesh._lightSources.indexOf(this) !== -1) {
  14838. mesh._markSubMeshesAsLightDirty();
  14839. }
  14840. }
  14841. };
  14842. /**
  14843. * Recomputes the cached photometric scale if needed.
  14844. */
  14845. Light.prototype._computePhotometricScale = function () {
  14846. this._photometricScale = this._getPhotometricScale();
  14847. this.getScene().resetCachedMaterial();
  14848. };
  14849. /**
  14850. * Returns the Photometric Scale according to the light type and intensity mode.
  14851. */
  14852. Light.prototype._getPhotometricScale = function () {
  14853. var photometricScale = 0.0;
  14854. var lightTypeID = this.getTypeID();
  14855. //get photometric mode
  14856. var photometricMode = this.intensityMode;
  14857. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14858. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14859. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14860. }
  14861. else {
  14862. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14863. }
  14864. }
  14865. //compute photometric scale
  14866. switch (lightTypeID) {
  14867. case Light.LIGHTTYPEID_POINTLIGHT:
  14868. case Light.LIGHTTYPEID_SPOTLIGHT:
  14869. switch (photometricMode) {
  14870. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14871. photometricScale = 1.0 / (4.0 * Math.PI);
  14872. break;
  14873. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14874. photometricScale = 1.0;
  14875. break;
  14876. case Light.INTENSITYMODE_LUMINANCE:
  14877. photometricScale = this.radius * this.radius;
  14878. break;
  14879. }
  14880. break;
  14881. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14882. switch (photometricMode) {
  14883. case Light.INTENSITYMODE_ILLUMINANCE:
  14884. photometricScale = 1.0;
  14885. break;
  14886. case Light.INTENSITYMODE_LUMINANCE:
  14887. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14888. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14889. var apexAngleRadians = this.radius;
  14890. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14891. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14892. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14893. photometricScale = solidAngle;
  14894. break;
  14895. }
  14896. break;
  14897. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14898. // No fall off in hemisperic light.
  14899. photometricScale = 1.0;
  14900. break;
  14901. }
  14902. return photometricScale;
  14903. };
  14904. Light.prototype._reorderLightsInScene = function () {
  14905. var scene = this.getScene();
  14906. if (this.renderPriority != 0) {
  14907. scene.requireLightSorting = true;
  14908. }
  14909. this.getScene().sortLightsByPriority();
  14910. };
  14911. //lightmapMode Consts
  14912. Light._LIGHTMAP_DEFAULT = 0;
  14913. Light._LIGHTMAP_SPECULAR = 1;
  14914. Light._LIGHTMAP_SHADOWSONLY = 2;
  14915. // Intensity Mode Consts
  14916. Light._INTENSITYMODE_AUTOMATIC = 0;
  14917. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14918. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14919. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14920. Light._INTENSITYMODE_LUMINANCE = 4;
  14921. // Light types ids const.
  14922. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14923. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14924. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14925. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14926. __decorate([
  14927. BABYLON.serializeAsColor3()
  14928. ], Light.prototype, "diffuse", void 0);
  14929. __decorate([
  14930. BABYLON.serializeAsColor3()
  14931. ], Light.prototype, "specular", void 0);
  14932. __decorate([
  14933. BABYLON.serialize()
  14934. ], Light.prototype, "intensity", void 0);
  14935. __decorate([
  14936. BABYLON.serialize()
  14937. ], Light.prototype, "range", void 0);
  14938. __decorate([
  14939. BABYLON.serialize()
  14940. ], Light.prototype, "intensityMode", null);
  14941. __decorate([
  14942. BABYLON.serialize()
  14943. ], Light.prototype, "radius", null);
  14944. __decorate([
  14945. BABYLON.serialize()
  14946. ], Light.prototype, "_renderPriority", void 0);
  14947. __decorate([
  14948. BABYLON.expandToProperty("_reorderLightsInScene")
  14949. ], Light.prototype, "renderPriority", void 0);
  14950. __decorate([
  14951. BABYLON.serialize()
  14952. ], Light.prototype, "shadowEnabled", void 0);
  14953. __decorate([
  14954. BABYLON.serialize("excludeWithLayerMask")
  14955. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14956. __decorate([
  14957. BABYLON.serialize("includeOnlyWithLayerMask")
  14958. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14959. __decorate([
  14960. BABYLON.serialize("lightmapMode")
  14961. ], Light.prototype, "_lightmapMode", void 0);
  14962. return Light;
  14963. }(BABYLON.Node));
  14964. BABYLON.Light = Light;
  14965. })(BABYLON || (BABYLON = {}));
  14966. //# sourceMappingURL=babylon.light.js.map
  14967. var BABYLON;
  14968. (function (BABYLON) {
  14969. var Camera = (function (_super) {
  14970. __extends(Camera, _super);
  14971. function Camera(name, position, scene) {
  14972. var _this = _super.call(this, name, scene) || this;
  14973. _this.upVector = BABYLON.Vector3.Up();
  14974. _this.orthoLeft = null;
  14975. _this.orthoRight = null;
  14976. _this.orthoBottom = null;
  14977. _this.orthoTop = null;
  14978. _this.fov = 0.8;
  14979. _this.minZ = 1;
  14980. _this.maxZ = 10000.0;
  14981. _this.inertia = 0.9;
  14982. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14983. _this.isIntermediate = false;
  14984. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14985. _this.layerMask = 0x0FFFFFFF;
  14986. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14987. // Camera rig members
  14988. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14989. _this._rigCameras = new Array();
  14990. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14991. _this._skipRendering = false;
  14992. _this.customRenderTargets = new Array();
  14993. // Observables
  14994. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14995. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14996. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14997. _this.onRestoreStateObservable = new BABYLON.Observable();
  14998. // Cache
  14999. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15000. _this._projectionMatrix = new BABYLON.Matrix();
  15001. _this._doNotComputeProjectionMatrix = false;
  15002. _this._postProcesses = new Array();
  15003. _this._transformMatrix = BABYLON.Matrix.Zero();
  15004. _this._activeMeshes = new BABYLON.SmartArray(256);
  15005. _this._globalPosition = BABYLON.Vector3.Zero();
  15006. _this._refreshFrustumPlanes = true;
  15007. _this.getScene().addCamera(_this);
  15008. if (!_this.getScene().activeCamera) {
  15009. _this.getScene().activeCamera = _this;
  15010. }
  15011. _this.position = position;
  15012. return _this;
  15013. }
  15014. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15015. get: function () {
  15016. return Camera._PERSPECTIVE_CAMERA;
  15017. },
  15018. enumerable: true,
  15019. configurable: true
  15020. });
  15021. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15022. get: function () {
  15023. return Camera._ORTHOGRAPHIC_CAMERA;
  15024. },
  15025. enumerable: true,
  15026. configurable: true
  15027. });
  15028. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15029. get: function () {
  15030. return Camera._FOVMODE_VERTICAL_FIXED;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15036. get: function () {
  15037. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15038. },
  15039. enumerable: true,
  15040. configurable: true
  15041. });
  15042. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15043. get: function () {
  15044. return Camera._RIG_MODE_NONE;
  15045. },
  15046. enumerable: true,
  15047. configurable: true
  15048. });
  15049. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15050. get: function () {
  15051. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15052. },
  15053. enumerable: true,
  15054. configurable: true
  15055. });
  15056. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15057. get: function () {
  15058. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15059. },
  15060. enumerable: true,
  15061. configurable: true
  15062. });
  15063. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15064. get: function () {
  15065. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15066. },
  15067. enumerable: true,
  15068. configurable: true
  15069. });
  15070. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15071. get: function () {
  15072. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15073. },
  15074. enumerable: true,
  15075. configurable: true
  15076. });
  15077. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15078. get: function () {
  15079. return Camera._RIG_MODE_VR;
  15080. },
  15081. enumerable: true,
  15082. configurable: true
  15083. });
  15084. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15085. get: function () {
  15086. return Camera._RIG_MODE_WEBVR;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. /**
  15092. * Store current camera state (fov, position, etc..)
  15093. */
  15094. Camera.prototype.storeState = function () {
  15095. this._stateStored = true;
  15096. this._storedFov = this.fov;
  15097. return this;
  15098. };
  15099. /**
  15100. * Restores the camera state values if it has been stored. You must call storeState() first
  15101. */
  15102. Camera.prototype._restoreStateValues = function () {
  15103. if (!this._stateStored) {
  15104. return false;
  15105. }
  15106. this.fov = this._storedFov;
  15107. return true;
  15108. };
  15109. /**
  15110. * Restored camera state. You must call storeState() first
  15111. */
  15112. Camera.prototype.restoreState = function () {
  15113. if (this._restoreStateValues()) {
  15114. this.onRestoreStateObservable.notifyObservers(this);
  15115. return true;
  15116. }
  15117. return false;
  15118. };
  15119. Camera.prototype.getClassName = function () {
  15120. return "Camera";
  15121. };
  15122. /**
  15123. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15124. */
  15125. Camera.prototype.toString = function (fullDetails) {
  15126. var ret = "Name: " + this.name;
  15127. ret += ", type: " + this.getClassName();
  15128. if (this.animations) {
  15129. for (var i = 0; i < this.animations.length; i++) {
  15130. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15131. }
  15132. }
  15133. if (fullDetails) {
  15134. }
  15135. return ret;
  15136. };
  15137. Object.defineProperty(Camera.prototype, "globalPosition", {
  15138. get: function () {
  15139. return this._globalPosition;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Camera.prototype.getActiveMeshes = function () {
  15145. return this._activeMeshes;
  15146. };
  15147. Camera.prototype.isActiveMesh = function (mesh) {
  15148. return (this._activeMeshes.indexOf(mesh) !== -1);
  15149. };
  15150. //Cache
  15151. Camera.prototype._initCache = function () {
  15152. _super.prototype._initCache.call(this);
  15153. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15154. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15155. this._cache.mode = undefined;
  15156. this._cache.minZ = undefined;
  15157. this._cache.maxZ = undefined;
  15158. this._cache.fov = undefined;
  15159. this._cache.fovMode = undefined;
  15160. this._cache.aspectRatio = undefined;
  15161. this._cache.orthoLeft = undefined;
  15162. this._cache.orthoRight = undefined;
  15163. this._cache.orthoBottom = undefined;
  15164. this._cache.orthoTop = undefined;
  15165. this._cache.renderWidth = undefined;
  15166. this._cache.renderHeight = undefined;
  15167. };
  15168. Camera.prototype._updateCache = function (ignoreParentClass) {
  15169. if (!ignoreParentClass) {
  15170. _super.prototype._updateCache.call(this);
  15171. }
  15172. var engine = this.getEngine();
  15173. this._cache.position.copyFrom(this.position);
  15174. this._cache.upVector.copyFrom(this.upVector);
  15175. };
  15176. // Synchronized
  15177. Camera.prototype._isSynchronized = function () {
  15178. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15179. };
  15180. Camera.prototype._isSynchronizedViewMatrix = function () {
  15181. if (!_super.prototype._isSynchronized.call(this))
  15182. return false;
  15183. return this._cache.position.equals(this.position)
  15184. && this._cache.upVector.equals(this.upVector)
  15185. && this.isSynchronizedWithParent();
  15186. };
  15187. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15188. var check = this._cache.mode === this.mode
  15189. && this._cache.minZ === this.minZ
  15190. && this._cache.maxZ === this.maxZ;
  15191. if (!check) {
  15192. return false;
  15193. }
  15194. var engine = this.getEngine();
  15195. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15196. check = this._cache.fov === this.fov
  15197. && this._cache.fovMode === this.fovMode
  15198. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15199. }
  15200. else {
  15201. check = this._cache.orthoLeft === this.orthoLeft
  15202. && this._cache.orthoRight === this.orthoRight
  15203. && this._cache.orthoBottom === this.orthoBottom
  15204. && this._cache.orthoTop === this.orthoTop
  15205. && this._cache.renderWidth === engine.getRenderWidth()
  15206. && this._cache.renderHeight === engine.getRenderHeight();
  15207. }
  15208. return check;
  15209. };
  15210. // Controls
  15211. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15212. };
  15213. Camera.prototype.detachControl = function (element) {
  15214. };
  15215. Camera.prototype.update = function () {
  15216. this._checkInputs();
  15217. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15218. this._updateRigCameras();
  15219. }
  15220. };
  15221. Camera.prototype._checkInputs = function () {
  15222. this.onAfterCheckInputsObservable.notifyObservers(this);
  15223. };
  15224. Object.defineProperty(Camera.prototype, "rigCameras", {
  15225. get: function () {
  15226. return this._rigCameras;
  15227. },
  15228. enumerable: true,
  15229. configurable: true
  15230. });
  15231. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15232. get: function () {
  15233. return this._rigPostProcess;
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15239. // invalidate framebuffer
  15240. if (this._postProcesses.length > 0) {
  15241. this._postProcesses[0].markTextureDirty();
  15242. }
  15243. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15244. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15245. var cam = this._rigCameras[i];
  15246. var rigPostProcess = cam._rigPostProcess;
  15247. // for VR rig, there does not have to be a post process
  15248. if (rigPostProcess) {
  15249. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15250. if (isPass) {
  15251. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15252. cam.isIntermediate = this._postProcesses.length === 0;
  15253. }
  15254. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15255. rigPostProcess.markTextureDirty();
  15256. }
  15257. else {
  15258. cam._postProcesses = this._postProcesses.slice(0);
  15259. }
  15260. }
  15261. };
  15262. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15263. if (insertAt === void 0) { insertAt = null; }
  15264. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15265. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15266. return 0;
  15267. }
  15268. if (insertAt == null || insertAt < 0) {
  15269. this._postProcesses.push(postProcess);
  15270. }
  15271. else {
  15272. this._postProcesses.splice(insertAt, 0, postProcess);
  15273. }
  15274. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15275. return this._postProcesses.indexOf(postProcess);
  15276. };
  15277. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15278. if (atIndices === void 0) { atIndices = null; }
  15279. var result = [];
  15280. var i;
  15281. var index;
  15282. if (!atIndices) {
  15283. var idx = this._postProcesses.indexOf(postProcess);
  15284. if (idx !== -1) {
  15285. this._postProcesses.splice(idx, 1);
  15286. }
  15287. }
  15288. else {
  15289. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15290. // iterate descending, so can just splice as we go
  15291. for (i = atIndices.length - 1; i >= 0; i--) {
  15292. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15293. result.push(i);
  15294. continue;
  15295. }
  15296. index = atIndices[i];
  15297. this._postProcesses.splice(index, 1);
  15298. }
  15299. }
  15300. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15301. return result;
  15302. };
  15303. Camera.prototype.getWorldMatrix = function () {
  15304. if (!this._worldMatrix) {
  15305. this._worldMatrix = BABYLON.Matrix.Identity();
  15306. }
  15307. var viewMatrix = this.getViewMatrix();
  15308. viewMatrix.invertToRef(this._worldMatrix);
  15309. return this._worldMatrix;
  15310. };
  15311. Camera.prototype._getViewMatrix = function () {
  15312. return BABYLON.Matrix.Identity();
  15313. };
  15314. Camera.prototype.getViewMatrix = function (force) {
  15315. if (!force && this._isSynchronizedViewMatrix()) {
  15316. return this._computedViewMatrix;
  15317. }
  15318. this.updateCache();
  15319. this._computedViewMatrix = this._getViewMatrix();
  15320. this._currentRenderId = this.getScene().getRenderId();
  15321. this._refreshFrustumPlanes = true;
  15322. if (!this.parent || !this.parent.getWorldMatrix) {
  15323. this._globalPosition.copyFrom(this.position);
  15324. }
  15325. else {
  15326. if (!this._worldMatrix) {
  15327. this._worldMatrix = BABYLON.Matrix.Identity();
  15328. }
  15329. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15330. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15331. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15332. this._computedViewMatrix.invert();
  15333. this._markSyncedWithParent();
  15334. }
  15335. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15336. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15337. }
  15338. this.onViewMatrixChangedObservable.notifyObservers(this);
  15339. return this._computedViewMatrix;
  15340. };
  15341. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15342. this._doNotComputeProjectionMatrix = true;
  15343. if (projection !== undefined) {
  15344. this._projectionMatrix = projection;
  15345. }
  15346. };
  15347. ;
  15348. Camera.prototype.unfreezeProjectionMatrix = function () {
  15349. this._doNotComputeProjectionMatrix = false;
  15350. };
  15351. ;
  15352. Camera.prototype.getProjectionMatrix = function (force) {
  15353. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15354. return this._projectionMatrix;
  15355. }
  15356. // Cache
  15357. this._cache.mode = this.mode;
  15358. this._cache.minZ = this.minZ;
  15359. this._cache.maxZ = this.maxZ;
  15360. // Matrix
  15361. this._refreshFrustumPlanes = true;
  15362. var engine = this.getEngine();
  15363. var scene = this.getScene();
  15364. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15365. this._cache.fov = this.fov;
  15366. this._cache.fovMode = this.fovMode;
  15367. this._cache.aspectRatio = engine.getAspectRatio(this);
  15368. if (this.minZ <= 0) {
  15369. this.minZ = 0.1;
  15370. }
  15371. if (scene.useRightHandedSystem) {
  15372. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15373. }
  15374. else {
  15375. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15376. }
  15377. }
  15378. else {
  15379. var halfWidth = engine.getRenderWidth() / 2.0;
  15380. var halfHeight = engine.getRenderHeight() / 2.0;
  15381. if (scene.useRightHandedSystem) {
  15382. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15383. }
  15384. else {
  15385. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15386. }
  15387. this._cache.orthoLeft = this.orthoLeft;
  15388. this._cache.orthoRight = this.orthoRight;
  15389. this._cache.orthoBottom = this.orthoBottom;
  15390. this._cache.orthoTop = this.orthoTop;
  15391. this._cache.renderWidth = engine.getRenderWidth();
  15392. this._cache.renderHeight = engine.getRenderHeight();
  15393. }
  15394. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15395. return this._projectionMatrix;
  15396. };
  15397. Camera.prototype.getTranformationMatrix = function () {
  15398. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15399. return this._transformMatrix;
  15400. };
  15401. Camera.prototype.updateFrustumPlanes = function () {
  15402. if (!this._refreshFrustumPlanes) {
  15403. return;
  15404. }
  15405. this.getTranformationMatrix();
  15406. if (!this._frustumPlanes) {
  15407. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15408. }
  15409. else {
  15410. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15411. }
  15412. this._refreshFrustumPlanes = false;
  15413. };
  15414. Camera.prototype.isInFrustum = function (target) {
  15415. this.updateFrustumPlanes();
  15416. return target.isInFrustum(this._frustumPlanes);
  15417. };
  15418. Camera.prototype.isCompletelyInFrustum = function (target) {
  15419. this.updateFrustumPlanes();
  15420. return target.isCompletelyInFrustum(this._frustumPlanes);
  15421. };
  15422. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15423. if (length === void 0) { length = 100; }
  15424. if (!transform) {
  15425. transform = this.getWorldMatrix();
  15426. }
  15427. if (!origin) {
  15428. origin = this.position;
  15429. }
  15430. var forward = new BABYLON.Vector3(0, 0, 1);
  15431. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15432. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15433. return new BABYLON.Ray(origin, direction, length);
  15434. };
  15435. Camera.prototype.dispose = function () {
  15436. // Observables
  15437. this.onViewMatrixChangedObservable.clear();
  15438. this.onProjectionMatrixChangedObservable.clear();
  15439. this.onAfterCheckInputsObservable.clear();
  15440. this.onRestoreStateObservable.clear();
  15441. // Inputs
  15442. if (this.inputs) {
  15443. this.inputs.clear();
  15444. }
  15445. // Animations
  15446. this.getScene().stopAnimation(this);
  15447. // Remove from scene
  15448. this.getScene().removeCamera(this);
  15449. while (this._rigCameras.length > 0) {
  15450. this._rigCameras.pop().dispose();
  15451. }
  15452. // Postprocesses
  15453. var i = this._postProcesses.length;
  15454. while (--i >= 0) {
  15455. this._postProcesses[i].dispose(this);
  15456. }
  15457. // Render targets
  15458. var i = this.customRenderTargets.length;
  15459. while (--i >= 0) {
  15460. this.customRenderTargets[i].dispose();
  15461. }
  15462. this.customRenderTargets = [];
  15463. // Active Meshes
  15464. this._activeMeshes.dispose();
  15465. _super.prototype.dispose.call(this);
  15466. };
  15467. Object.defineProperty(Camera.prototype, "leftCamera", {
  15468. // ---- Camera rigs section ----
  15469. get: function () {
  15470. if (this._rigCameras.length < 1) {
  15471. return undefined;
  15472. }
  15473. return this._rigCameras[0];
  15474. },
  15475. enumerable: true,
  15476. configurable: true
  15477. });
  15478. Object.defineProperty(Camera.prototype, "rightCamera", {
  15479. get: function () {
  15480. if (this._rigCameras.length < 2) {
  15481. return undefined;
  15482. }
  15483. return this._rigCameras[1];
  15484. },
  15485. enumerable: true,
  15486. configurable: true
  15487. });
  15488. Camera.prototype.getLeftTarget = function () {
  15489. if (this._rigCameras.length < 1) {
  15490. return undefined;
  15491. }
  15492. return this._rigCameras[0].getTarget();
  15493. };
  15494. Camera.prototype.getRightTarget = function () {
  15495. if (this._rigCameras.length < 2) {
  15496. return undefined;
  15497. }
  15498. return this._rigCameras[1].getTarget();
  15499. };
  15500. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15501. while (this._rigCameras.length > 0) {
  15502. this._rigCameras.pop().dispose();
  15503. }
  15504. this.cameraRigMode = mode;
  15505. this._cameraRigParams = {};
  15506. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15507. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15508. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15509. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15510. // create the rig cameras, unless none
  15511. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15512. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15513. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15514. }
  15515. switch (this.cameraRigMode) {
  15516. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15517. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15518. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15519. break;
  15520. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15521. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15522. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15523. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15524. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15525. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15526. break;
  15527. case Camera.RIG_MODE_VR:
  15528. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15529. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15530. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15531. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15532. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15533. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15534. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15535. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15536. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15537. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15538. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15539. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15540. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15541. if (metrics.compensateDistortion) {
  15542. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15543. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15544. }
  15545. break;
  15546. case Camera.RIG_MODE_WEBVR:
  15547. if (rigParams.vrDisplay) {
  15548. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15549. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15550. //Left eye
  15551. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15552. this._rigCameras[0].setCameraRigParameter("left", true);
  15553. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15554. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15555. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15556. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15557. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15558. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15559. this._rigCameras[0].parent = this;
  15560. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15561. //Right eye
  15562. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15563. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15564. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15565. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15566. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15567. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15568. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15569. this._rigCameras[1].parent = this;
  15570. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15571. if (Camera.UseAlternateWebVRRendering) {
  15572. this._rigCameras[1]._skipRendering = true;
  15573. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15574. }
  15575. }
  15576. break;
  15577. }
  15578. this._cascadePostProcessesToRigCams();
  15579. this.update();
  15580. };
  15581. Camera.prototype._getVRProjectionMatrix = function () {
  15582. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15583. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15584. return this._projectionMatrix;
  15585. };
  15586. Camera.prototype._updateCameraRotationMatrix = function () {
  15587. //Here for WebVR
  15588. };
  15589. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15590. //Here for WebVR
  15591. };
  15592. /**
  15593. * This function MUST be overwritten by the different WebVR cameras available.
  15594. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15595. */
  15596. Camera.prototype._getWebVRProjectionMatrix = function () {
  15597. return BABYLON.Matrix.Identity();
  15598. };
  15599. /**
  15600. * This function MUST be overwritten by the different WebVR cameras available.
  15601. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15602. */
  15603. Camera.prototype._getWebVRViewMatrix = function () {
  15604. return BABYLON.Matrix.Identity();
  15605. };
  15606. Camera.prototype.setCameraRigParameter = function (name, value) {
  15607. if (!this._cameraRigParams) {
  15608. this._cameraRigParams = {};
  15609. }
  15610. this._cameraRigParams[name] = value;
  15611. //provisionnally:
  15612. if (name === "interaxialDistance") {
  15613. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15614. }
  15615. };
  15616. /**
  15617. * needs to be overridden by children so sub has required properties to be copied
  15618. */
  15619. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15620. return null;
  15621. };
  15622. /**
  15623. * May need to be overridden by children
  15624. */
  15625. Camera.prototype._updateRigCameras = function () {
  15626. for (var i = 0; i < this._rigCameras.length; i++) {
  15627. this._rigCameras[i].minZ = this.minZ;
  15628. this._rigCameras[i].maxZ = this.maxZ;
  15629. this._rigCameras[i].fov = this.fov;
  15630. }
  15631. // only update viewport when ANAGLYPH
  15632. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15633. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15634. }
  15635. };
  15636. Camera.prototype._setupInputs = function () {
  15637. };
  15638. Camera.prototype.serialize = function () {
  15639. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15640. // Type
  15641. serializationObject.type = this.getClassName();
  15642. // Parent
  15643. if (this.parent) {
  15644. serializationObject.parentId = this.parent.id;
  15645. }
  15646. if (this.inputs) {
  15647. this.inputs.serialize(serializationObject);
  15648. }
  15649. // Animations
  15650. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15651. serializationObject.ranges = this.serializeAnimationRanges();
  15652. return serializationObject;
  15653. };
  15654. Camera.prototype.clone = function (name) {
  15655. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15656. };
  15657. Camera.prototype.getDirection = function (localAxis) {
  15658. var result = BABYLON.Vector3.Zero();
  15659. this.getDirectionToRef(localAxis, result);
  15660. return result;
  15661. };
  15662. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15663. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15664. };
  15665. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15666. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15667. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15668. switch (type) {
  15669. case "ArcRotateCamera":
  15670. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15671. case "DeviceOrientationCamera":
  15672. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15673. case "FollowCamera":
  15674. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15675. case "ArcFollowCamera":
  15676. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15677. case "GamepadCamera":
  15678. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15679. case "TouchCamera":
  15680. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15681. case "VirtualJoysticksCamera":
  15682. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15683. case "WebVRFreeCamera":
  15684. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15685. case "WebVRGamepadCamera":
  15686. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15687. case "VRDeviceOrientationFreeCamera":
  15688. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15689. case "VRDeviceOrientationGamepadCamera":
  15690. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15691. case "AnaglyphArcRotateCamera":
  15692. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15693. case "AnaglyphFreeCamera":
  15694. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15695. case "AnaglyphGamepadCamera":
  15696. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15697. case "AnaglyphUniversalCamera":
  15698. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15699. case "StereoscopicArcRotateCamera":
  15700. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15701. case "StereoscopicFreeCamera":
  15702. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15703. case "StereoscopicGamepadCamera":
  15704. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15705. case "StereoscopicUniversalCamera":
  15706. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15707. case "FreeCamera":// Forcing Universal here
  15708. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15709. default:// Universal Camera is the default value
  15710. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15711. }
  15712. };
  15713. Camera.Parse = function (parsedCamera, scene) {
  15714. var type = parsedCamera.type;
  15715. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15716. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15717. // Parent
  15718. if (parsedCamera.parentId) {
  15719. camera._waitingParentId = parsedCamera.parentId;
  15720. }
  15721. //If camera has an input manager, let it parse inputs settings
  15722. if (camera.inputs) {
  15723. camera.inputs.parse(parsedCamera);
  15724. camera._setupInputs();
  15725. }
  15726. if (camera.setPosition) {
  15727. camera.position.copyFromFloats(0, 0, 0);
  15728. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15729. }
  15730. // Target
  15731. if (parsedCamera.target) {
  15732. if (camera.setTarget) {
  15733. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15734. }
  15735. }
  15736. // Apply 3d rig, when found
  15737. if (parsedCamera.cameraRigMode) {
  15738. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15739. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15740. }
  15741. // Animations
  15742. if (parsedCamera.animations) {
  15743. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15744. var parsedAnimation = parsedCamera.animations[animationIndex];
  15745. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15746. }
  15747. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15748. }
  15749. if (parsedCamera.autoAnimate) {
  15750. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15751. }
  15752. return camera;
  15753. };
  15754. // Statics
  15755. Camera._PERSPECTIVE_CAMERA = 0;
  15756. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15757. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15758. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15759. Camera._RIG_MODE_NONE = 0;
  15760. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15761. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15762. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15763. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15764. Camera._RIG_MODE_VR = 20;
  15765. Camera._RIG_MODE_WEBVR = 21;
  15766. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15767. Camera.UseAlternateWebVRRendering = false;
  15768. __decorate([
  15769. BABYLON.serializeAsVector3()
  15770. ], Camera.prototype, "position", void 0);
  15771. __decorate([
  15772. BABYLON.serializeAsVector3()
  15773. ], Camera.prototype, "upVector", void 0);
  15774. __decorate([
  15775. BABYLON.serialize()
  15776. ], Camera.prototype, "orthoLeft", void 0);
  15777. __decorate([
  15778. BABYLON.serialize()
  15779. ], Camera.prototype, "orthoRight", void 0);
  15780. __decorate([
  15781. BABYLON.serialize()
  15782. ], Camera.prototype, "orthoBottom", void 0);
  15783. __decorate([
  15784. BABYLON.serialize()
  15785. ], Camera.prototype, "orthoTop", void 0);
  15786. __decorate([
  15787. BABYLON.serialize()
  15788. ], Camera.prototype, "fov", void 0);
  15789. __decorate([
  15790. BABYLON.serialize()
  15791. ], Camera.prototype, "minZ", void 0);
  15792. __decorate([
  15793. BABYLON.serialize()
  15794. ], Camera.prototype, "maxZ", void 0);
  15795. __decorate([
  15796. BABYLON.serialize()
  15797. ], Camera.prototype, "inertia", void 0);
  15798. __decorate([
  15799. BABYLON.serialize()
  15800. ], Camera.prototype, "mode", void 0);
  15801. __decorate([
  15802. BABYLON.serialize()
  15803. ], Camera.prototype, "layerMask", void 0);
  15804. __decorate([
  15805. BABYLON.serialize()
  15806. ], Camera.prototype, "fovMode", void 0);
  15807. __decorate([
  15808. BABYLON.serialize()
  15809. ], Camera.prototype, "cameraRigMode", void 0);
  15810. __decorate([
  15811. BABYLON.serialize()
  15812. ], Camera.prototype, "interaxialDistance", void 0);
  15813. __decorate([
  15814. BABYLON.serialize()
  15815. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15816. return Camera;
  15817. }(BABYLON.Node));
  15818. BABYLON.Camera = Camera;
  15819. })(BABYLON || (BABYLON = {}));
  15820. //# sourceMappingURL=babylon.camera.js.map
  15821. var BABYLON;
  15822. (function (BABYLON) {
  15823. var RenderingManager = (function () {
  15824. function RenderingManager(scene) {
  15825. this._renderingGroups = new Array();
  15826. this._autoClearDepthStencil = {};
  15827. this._customOpaqueSortCompareFn = {};
  15828. this._customAlphaTestSortCompareFn = {};
  15829. this._customTransparentSortCompareFn = {};
  15830. this._renderinGroupInfo = null;
  15831. this._scene = scene;
  15832. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15833. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15834. }
  15835. }
  15836. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15837. if (depth === void 0) { depth = true; }
  15838. if (stencil === void 0) { stencil = true; }
  15839. if (this._depthStencilBufferAlreadyCleaned) {
  15840. return;
  15841. }
  15842. this._scene.getEngine().clear(null, false, depth, stencil);
  15843. this._depthStencilBufferAlreadyCleaned = true;
  15844. };
  15845. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15846. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15847. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15848. var info = null;
  15849. if (observable) {
  15850. if (!this._renderinGroupInfo) {
  15851. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15852. }
  15853. info = this._renderinGroupInfo;
  15854. info.scene = this._scene;
  15855. info.camera = this._scene.activeCamera;
  15856. }
  15857. // Dispatch sprites
  15858. if (renderSprites) {
  15859. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15860. var manager = this._scene.spriteManagers[index];
  15861. this.dispatchSprites(manager);
  15862. }
  15863. }
  15864. // Render
  15865. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15866. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15867. var renderingGroup = this._renderingGroups[index];
  15868. if (!renderingGroup && !observable)
  15869. continue;
  15870. this._currentIndex = index;
  15871. var renderingGroupMask = 0;
  15872. // Fire PRECLEAR stage
  15873. if (observable) {
  15874. renderingGroupMask = Math.pow(2, index);
  15875. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15876. info.renderingGroupId = index;
  15877. observable.notifyObservers(info, renderingGroupMask);
  15878. }
  15879. // Clear depth/stencil if needed
  15880. if (RenderingManager.AUTOCLEAR) {
  15881. var autoClear = this._autoClearDepthStencil[index];
  15882. if (autoClear && autoClear.autoClear) {
  15883. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15884. }
  15885. }
  15886. if (observable) {
  15887. // Fire PREOPAQUE stage
  15888. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15889. observable.notifyObservers(info, renderingGroupMask);
  15890. // Fire PRETRANSPARENT stage
  15891. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15892. observable.notifyObservers(info, renderingGroupMask);
  15893. }
  15894. if (renderingGroup)
  15895. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15896. // Fire POSTTRANSPARENT stage
  15897. if (observable) {
  15898. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15899. observable.notifyObservers(info, renderingGroupMask);
  15900. }
  15901. }
  15902. };
  15903. RenderingManager.prototype.reset = function () {
  15904. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15905. var renderingGroup = this._renderingGroups[index];
  15906. if (renderingGroup) {
  15907. renderingGroup.prepare();
  15908. }
  15909. }
  15910. };
  15911. RenderingManager.prototype.dispose = function () {
  15912. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15913. var renderingGroup = this._renderingGroups[index];
  15914. if (renderingGroup) {
  15915. renderingGroup.dispose();
  15916. }
  15917. }
  15918. this._renderingGroups.length = 0;
  15919. };
  15920. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15921. if (!this._renderingGroups[renderingGroupId]) {
  15922. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15923. }
  15924. };
  15925. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15926. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15927. this._prepareRenderingGroup(renderingGroupId);
  15928. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15929. };
  15930. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15931. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15932. this._prepareRenderingGroup(renderingGroupId);
  15933. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15934. };
  15935. RenderingManager.prototype.dispatch = function (subMesh) {
  15936. var mesh = subMesh.getMesh();
  15937. var renderingGroupId = mesh.renderingGroupId || 0;
  15938. this._prepareRenderingGroup(renderingGroupId);
  15939. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15940. };
  15941. /**
  15942. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15943. * This allowed control for front to back rendering or reversly depending of the special needs.
  15944. *
  15945. * @param renderingGroupId The rendering group id corresponding to its index
  15946. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15947. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15948. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15949. */
  15950. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15951. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15952. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15953. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15954. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15955. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15956. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15957. if (this._renderingGroups[renderingGroupId]) {
  15958. var group = this._renderingGroups[renderingGroupId];
  15959. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15960. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15961. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15962. }
  15963. };
  15964. /**
  15965. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15966. *
  15967. * @param renderingGroupId The rendering group id corresponding to its index
  15968. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15969. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15970. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15971. */
  15972. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15973. if (depth === void 0) { depth = true; }
  15974. if (stencil === void 0) { stencil = true; }
  15975. this._autoClearDepthStencil[renderingGroupId] = {
  15976. autoClear: autoClearDepthStencil,
  15977. depth: depth,
  15978. stencil: stencil
  15979. };
  15980. };
  15981. /**
  15982. * The max id used for rendering groups (not included)
  15983. */
  15984. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15985. /**
  15986. * The min id used for rendering groups (included)
  15987. */
  15988. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15989. /**
  15990. * Used to globally prevent autoclearing scenes.
  15991. */
  15992. RenderingManager.AUTOCLEAR = true;
  15993. return RenderingManager;
  15994. }());
  15995. BABYLON.RenderingManager = RenderingManager;
  15996. })(BABYLON || (BABYLON = {}));
  15997. //# sourceMappingURL=babylon.renderingManager.js.map
  15998. var BABYLON;
  15999. (function (BABYLON) {
  16000. var RenderingGroup = (function () {
  16001. /**
  16002. * Creates a new rendering group.
  16003. * @param index The rendering group index
  16004. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16005. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16006. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16007. */
  16008. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16009. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16010. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16011. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16012. this.index = index;
  16013. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16014. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16015. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16016. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16017. this._particleSystems = new BABYLON.SmartArray(256);
  16018. this._spriteManagers = new BABYLON.SmartArray(256);
  16019. this._edgesRenderers = new BABYLON.SmartArray(16);
  16020. this._scene = scene;
  16021. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16022. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16023. this.transparentSortCompareFn = transparentSortCompareFn;
  16024. }
  16025. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16026. /**
  16027. * Set the opaque sort comparison function.
  16028. * If null the sub meshes will be render in the order they were created
  16029. */
  16030. set: function (value) {
  16031. this._opaqueSortCompareFn = value;
  16032. if (value) {
  16033. this._renderOpaque = this.renderOpaqueSorted;
  16034. }
  16035. else {
  16036. this._renderOpaque = RenderingGroup.renderUnsorted;
  16037. }
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16043. /**
  16044. * Set the alpha test sort comparison function.
  16045. * If null the sub meshes will be render in the order they were created
  16046. */
  16047. set: function (value) {
  16048. this._alphaTestSortCompareFn = value;
  16049. if (value) {
  16050. this._renderAlphaTest = this.renderAlphaTestSorted;
  16051. }
  16052. else {
  16053. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16054. }
  16055. },
  16056. enumerable: true,
  16057. configurable: true
  16058. });
  16059. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16060. /**
  16061. * Set the transparent sort comparison function.
  16062. * If null the sub meshes will be render in the order they were created
  16063. */
  16064. set: function (value) {
  16065. if (value) {
  16066. this._transparentSortCompareFn = value;
  16067. }
  16068. else {
  16069. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16070. }
  16071. this._renderTransparent = this.renderTransparentSorted;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. /**
  16077. * Render all the sub meshes contained in the group.
  16078. * @param customRenderFunction Used to override the default render behaviour of the group.
  16079. * @returns true if rendered some submeshes.
  16080. */
  16081. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16082. if (customRenderFunction) {
  16083. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16084. return;
  16085. }
  16086. var engine = this._scene.getEngine();
  16087. // Depth only
  16088. if (this._depthOnlySubMeshes.length !== 0) {
  16089. engine.setAlphaTesting(true);
  16090. engine.setColorWrite(false);
  16091. this._renderAlphaTest(this._depthOnlySubMeshes);
  16092. engine.setAlphaTesting(false);
  16093. engine.setColorWrite(true);
  16094. }
  16095. // Opaque
  16096. if (this._opaqueSubMeshes.length !== 0) {
  16097. this._renderOpaque(this._opaqueSubMeshes);
  16098. }
  16099. // Alpha test
  16100. if (this._alphaTestSubMeshes.length !== 0) {
  16101. engine.setAlphaTesting(true);
  16102. this._renderAlphaTest(this._alphaTestSubMeshes);
  16103. engine.setAlphaTesting(false);
  16104. }
  16105. var stencilState = engine.getStencilBuffer();
  16106. engine.setStencilBuffer(false);
  16107. // Sprites
  16108. if (renderSprites) {
  16109. this._renderSprites();
  16110. }
  16111. // Particles
  16112. if (renderParticles) {
  16113. this._renderParticles(activeMeshes);
  16114. }
  16115. if (this.onBeforeTransparentRendering) {
  16116. this.onBeforeTransparentRendering();
  16117. }
  16118. // Transparent
  16119. if (this._transparentSubMeshes.length !== 0) {
  16120. this._renderTransparent(this._transparentSubMeshes);
  16121. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16122. }
  16123. // Set back stencil to false in case it changes before the edge renderer.
  16124. engine.setStencilBuffer(false);
  16125. // Edges
  16126. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16127. this._edgesRenderers.data[edgesRendererIndex].render();
  16128. }
  16129. // Restore Stencil state.
  16130. engine.setStencilBuffer(stencilState);
  16131. };
  16132. /**
  16133. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16134. * @param subMeshes The submeshes to render
  16135. */
  16136. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16137. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16138. };
  16139. /**
  16140. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16141. * @param subMeshes The submeshes to render
  16142. */
  16143. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16144. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16145. };
  16146. /**
  16147. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16148. * @param subMeshes The submeshes to render
  16149. */
  16150. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16151. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16152. };
  16153. /**
  16154. * Renders the submeshes in a specified order.
  16155. * @param subMeshes The submeshes to sort before render
  16156. * @param sortCompareFn The comparison function use to sort
  16157. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16158. * @param transparent Specifies to activate blending if true
  16159. */
  16160. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16161. var subIndex = 0;
  16162. var subMesh;
  16163. for (; subIndex < subMeshes.length; subIndex++) {
  16164. subMesh = subMeshes.data[subIndex];
  16165. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16166. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16167. }
  16168. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16169. sortedArray.sort(sortCompareFn);
  16170. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16171. subMesh = sortedArray[subIndex];
  16172. if (transparent) {
  16173. var material = subMesh.getMaterial();
  16174. if (material.needDepthPrePass) {
  16175. var engine = material.getScene().getEngine();
  16176. engine.setColorWrite(false);
  16177. engine.setAlphaTesting(true);
  16178. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16179. subMesh.render(false);
  16180. engine.setAlphaTesting(false);
  16181. engine.setColorWrite(true);
  16182. }
  16183. }
  16184. subMesh.render(transparent);
  16185. }
  16186. };
  16187. /**
  16188. * Renders the submeshes in the order they were dispatched (no sort applied).
  16189. * @param subMeshes The submeshes to render
  16190. */
  16191. RenderingGroup.renderUnsorted = function (subMeshes) {
  16192. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16193. var submesh = subMeshes.data[subIndex];
  16194. submesh.render(false);
  16195. }
  16196. };
  16197. /**
  16198. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16199. * are rendered back to front if in the same alpha index.
  16200. *
  16201. * @param a The first submesh
  16202. * @param b The second submesh
  16203. * @returns The result of the comparison
  16204. */
  16205. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16206. // Alpha index first
  16207. if (a._alphaIndex > b._alphaIndex) {
  16208. return 1;
  16209. }
  16210. if (a._alphaIndex < b._alphaIndex) {
  16211. return -1;
  16212. }
  16213. // Then distance to camera
  16214. return RenderingGroup.backToFrontSortCompare(a, b);
  16215. };
  16216. /**
  16217. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16218. * are rendered back to front.
  16219. *
  16220. * @param a The first submesh
  16221. * @param b The second submesh
  16222. * @returns The result of the comparison
  16223. */
  16224. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16225. // Then distance to camera
  16226. if (a._distanceToCamera < b._distanceToCamera) {
  16227. return 1;
  16228. }
  16229. if (a._distanceToCamera > b._distanceToCamera) {
  16230. return -1;
  16231. }
  16232. return 0;
  16233. };
  16234. /**
  16235. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16236. * are rendered front to back (prevent overdraw).
  16237. *
  16238. * @param a The first submesh
  16239. * @param b The second submesh
  16240. * @returns The result of the comparison
  16241. */
  16242. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16243. // Then distance to camera
  16244. if (a._distanceToCamera < b._distanceToCamera) {
  16245. return -1;
  16246. }
  16247. if (a._distanceToCamera > b._distanceToCamera) {
  16248. return 1;
  16249. }
  16250. return 0;
  16251. };
  16252. /**
  16253. * Resets the different lists of submeshes to prepare a new frame.
  16254. */
  16255. RenderingGroup.prototype.prepare = function () {
  16256. this._opaqueSubMeshes.reset();
  16257. this._transparentSubMeshes.reset();
  16258. this._alphaTestSubMeshes.reset();
  16259. this._depthOnlySubMeshes.reset();
  16260. this._particleSystems.reset();
  16261. this._spriteManagers.reset();
  16262. this._edgesRenderers.reset();
  16263. };
  16264. RenderingGroup.prototype.dispose = function () {
  16265. this._opaqueSubMeshes.dispose();
  16266. this._transparentSubMeshes.dispose();
  16267. this._alphaTestSubMeshes.dispose();
  16268. this._depthOnlySubMeshes.dispose();
  16269. this._particleSystems.dispose();
  16270. this._spriteManagers.dispose();
  16271. this._edgesRenderers.dispose();
  16272. };
  16273. /**
  16274. * Inserts the submesh in its correct queue depending on its material.
  16275. * @param subMesh The submesh to dispatch
  16276. */
  16277. RenderingGroup.prototype.dispatch = function (subMesh) {
  16278. var material = subMesh.getMaterial();
  16279. var mesh = subMesh.getMesh();
  16280. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16281. this._transparentSubMeshes.push(subMesh);
  16282. }
  16283. else if (material.needAlphaTesting()) {
  16284. if (material.needDepthPrePass) {
  16285. this._depthOnlySubMeshes.push(subMesh);
  16286. }
  16287. this._alphaTestSubMeshes.push(subMesh);
  16288. }
  16289. else {
  16290. if (material.needDepthPrePass) {
  16291. this._depthOnlySubMeshes.push(subMesh);
  16292. }
  16293. this._opaqueSubMeshes.push(subMesh); // Opaque
  16294. }
  16295. if (mesh._edgesRenderer) {
  16296. this._edgesRenderers.push(mesh._edgesRenderer);
  16297. }
  16298. };
  16299. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16300. this._spriteManagers.push(spriteManager);
  16301. };
  16302. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16303. this._particleSystems.push(particleSystem);
  16304. };
  16305. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16306. if (this._particleSystems.length === 0) {
  16307. return;
  16308. }
  16309. // Particles
  16310. var activeCamera = this._scene.activeCamera;
  16311. this._scene._particlesDuration.beginMonitoring();
  16312. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16313. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16314. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16315. continue;
  16316. }
  16317. var emitter = particleSystem.emitter;
  16318. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16319. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16320. }
  16321. }
  16322. this._scene._particlesDuration.endMonitoring(false);
  16323. };
  16324. RenderingGroup.prototype._renderSprites = function () {
  16325. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16326. return;
  16327. }
  16328. // Sprites
  16329. var activeCamera = this._scene.activeCamera;
  16330. this._scene._spritesDuration.beginMonitoring();
  16331. for (var id = 0; id < this._spriteManagers.length; id++) {
  16332. var spriteManager = this._spriteManagers.data[id];
  16333. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16334. spriteManager.render();
  16335. }
  16336. }
  16337. this._scene._spritesDuration.endMonitoring(false);
  16338. };
  16339. return RenderingGroup;
  16340. }());
  16341. BABYLON.RenderingGroup = RenderingGroup;
  16342. })(BABYLON || (BABYLON = {}));
  16343. //# sourceMappingURL=babylon.renderingGroup.js.map
  16344. var BABYLON;
  16345. (function (BABYLON) {
  16346. var ClickInfo = (function () {
  16347. function ClickInfo() {
  16348. this._singleClick = false;
  16349. this._doubleClick = false;
  16350. this._hasSwiped = false;
  16351. this._ignore = false;
  16352. }
  16353. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16354. get: function () {
  16355. return this._singleClick;
  16356. },
  16357. set: function (b) {
  16358. this._singleClick = b;
  16359. },
  16360. enumerable: true,
  16361. configurable: true
  16362. });
  16363. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16364. get: function () {
  16365. return this._doubleClick;
  16366. },
  16367. set: function (b) {
  16368. this._doubleClick = b;
  16369. },
  16370. enumerable: true,
  16371. configurable: true
  16372. });
  16373. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16374. get: function () {
  16375. return this._hasSwiped;
  16376. },
  16377. set: function (b) {
  16378. this._hasSwiped = b;
  16379. },
  16380. enumerable: true,
  16381. configurable: true
  16382. });
  16383. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16384. get: function () {
  16385. return this._ignore;
  16386. },
  16387. set: function (b) {
  16388. this._ignore = b;
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. return ClickInfo;
  16394. }());
  16395. /**
  16396. * This class is used by the onRenderingGroupObservable
  16397. */
  16398. var RenderingGroupInfo = (function () {
  16399. function RenderingGroupInfo() {
  16400. }
  16401. /**
  16402. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16403. * This stage will be fired no matter what
  16404. */
  16405. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16406. /**
  16407. * Called before opaque object are rendered.
  16408. * This stage will be fired only if there's 3D Opaque content to render
  16409. */
  16410. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16411. /**
  16412. * Called after the opaque objects are rendered and before the transparent ones
  16413. * This stage will be fired only if there's 3D transparent content to render
  16414. */
  16415. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16416. /**
  16417. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16418. * This stage will be fired no matter what
  16419. */
  16420. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16421. return RenderingGroupInfo;
  16422. }());
  16423. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16424. /**
  16425. * Represents a scene to be rendered by the engine.
  16426. * @see http://doc.babylonjs.com/page.php?p=21911
  16427. */
  16428. var Scene = (function () {
  16429. /**
  16430. * @constructor
  16431. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16432. */
  16433. function Scene(engine) {
  16434. // Members
  16435. this.autoClear = true;
  16436. this.autoClearDepthAndStencil = true;
  16437. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16438. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16439. this.forceWireframe = false;
  16440. this._forcePointsCloud = false;
  16441. this.forceShowBoundingBoxes = false;
  16442. this.animationsEnabled = true;
  16443. this.constantlyUpdateMeshUnderPointer = false;
  16444. this.hoverCursor = "pointer";
  16445. this.defaultCursor = "";
  16446. // Metadata
  16447. this.metadata = null;
  16448. /**
  16449. * An event triggered when the scene is disposed.
  16450. * @type {BABYLON.Observable}
  16451. */
  16452. this.onDisposeObservable = new BABYLON.Observable();
  16453. /**
  16454. * An event triggered before rendering the scene
  16455. * @type {BABYLON.Observable}
  16456. */
  16457. this.onBeforeRenderObservable = new BABYLON.Observable();
  16458. /**
  16459. * An event triggered after rendering the scene
  16460. * @type {BABYLON.Observable}
  16461. */
  16462. this.onAfterRenderObservable = new BABYLON.Observable();
  16463. /**
  16464. * An event triggered when the scene is ready
  16465. * @type {BABYLON.Observable}
  16466. */
  16467. this.onReadyObservable = new BABYLON.Observable();
  16468. /**
  16469. * An event triggered before rendering a camera
  16470. * @type {BABYLON.Observable}
  16471. */
  16472. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16473. /**
  16474. * An event triggered after rendering a camera
  16475. * @type {BABYLON.Observable}
  16476. */
  16477. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16478. /**
  16479. * An event triggered when a camera is created
  16480. * @type {BABYLON.Observable}
  16481. */
  16482. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16483. /**
  16484. * An event triggered when a camera is removed
  16485. * @type {BABYLON.Observable}
  16486. */
  16487. this.onCameraRemovedObservable = new BABYLON.Observable();
  16488. /**
  16489. * An event triggered when a light is created
  16490. * @type {BABYLON.Observable}
  16491. */
  16492. this.onNewLightAddedObservable = new BABYLON.Observable();
  16493. /**
  16494. * An event triggered when a light is removed
  16495. * @type {BABYLON.Observable}
  16496. */
  16497. this.onLightRemovedObservable = new BABYLON.Observable();
  16498. /**
  16499. * An event triggered when a geometry is created
  16500. * @type {BABYLON.Observable}
  16501. */
  16502. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16503. /**
  16504. * An event triggered when a geometry is removed
  16505. * @type {BABYLON.Observable}
  16506. */
  16507. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16508. /**
  16509. * An event triggered when a mesh is created
  16510. * @type {BABYLON.Observable}
  16511. */
  16512. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16513. /**
  16514. * An event triggered when a mesh is removed
  16515. * @type {BABYLON.Observable}
  16516. */
  16517. this.onMeshRemovedObservable = new BABYLON.Observable();
  16518. /**
  16519. * An event triggered before calculating deterministic simulation step
  16520. * @type {BABYLON.Observable}
  16521. */
  16522. this.onBeforeStepObservable = new BABYLON.Observable();
  16523. /**
  16524. * An event triggered after calculating deterministic simulation step
  16525. * @type {BABYLON.Observable}
  16526. */
  16527. this.onAfterStepObservable = new BABYLON.Observable();
  16528. /**
  16529. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16530. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16531. * 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)
  16532. */
  16533. this.onRenderingGroupObservable = new BABYLON.Observable();
  16534. // Animations
  16535. this.animations = [];
  16536. /**
  16537. * 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).
  16538. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16539. */
  16540. this.onPrePointerObservable = new BABYLON.Observable();
  16541. /**
  16542. * Observable event triggered each time an input event is received from the rendering canvas
  16543. */
  16544. this.onPointerObservable = new BABYLON.Observable();
  16545. this._meshPickProceed = false;
  16546. this._previousHasSwiped = false;
  16547. this._currentPickResult = null;
  16548. this._previousPickResult = null;
  16549. this._isButtonPressed = false;
  16550. this._doubleClickOccured = false;
  16551. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16552. this.cameraToUseForPointers = null;
  16553. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16554. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16555. this._startingPointerTime = 0;
  16556. this._previousStartingPointerTime = 0;
  16557. // Deterministic lockstep
  16558. this._timeAccumulator = 0;
  16559. this._currentStepId = 0;
  16560. this._currentInternalStep = 0;
  16561. // Keyboard
  16562. /**
  16563. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16564. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16565. */
  16566. this.onPreKeyboardObservable = new BABYLON.Observable();
  16567. /**
  16568. * Observable event triggered each time an keyboard event is received from the hosting window
  16569. */
  16570. this.onKeyboardObservable = new BABYLON.Observable();
  16571. // Coordinate system
  16572. /**
  16573. * use right-handed coordinate system on this scene.
  16574. * @type {boolean}
  16575. */
  16576. this._useRightHandedSystem = false;
  16577. // Fog
  16578. this._fogEnabled = true;
  16579. this._fogMode = Scene.FOGMODE_NONE;
  16580. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16581. this.fogDensity = 0.1;
  16582. this.fogStart = 0;
  16583. this.fogEnd = 1000.0;
  16584. // Lights
  16585. /**
  16586. * is shadow enabled on this scene.
  16587. * @type {boolean}
  16588. */
  16589. this._shadowsEnabled = true;
  16590. /**
  16591. * is light enabled on this scene.
  16592. * @type {boolean}
  16593. */
  16594. this._lightsEnabled = true;
  16595. /**
  16596. * All of the lights added to this scene.
  16597. * @see BABYLON.Light
  16598. * @type {BABYLON.Light[]}
  16599. */
  16600. this.lights = new Array();
  16601. // Cameras
  16602. /** All of the cameras added to this scene. */
  16603. this.cameras = new Array();
  16604. /** All of the active cameras added to this scene. */
  16605. this.activeCameras = new Array();
  16606. // Meshes
  16607. /**
  16608. * All of the (abstract) meshes added to this scene.
  16609. * @see BABYLON.AbstractMesh
  16610. * @type {BABYLON.AbstractMesh[]}
  16611. */
  16612. this.meshes = new Array();
  16613. // Geometries
  16614. this._geometries = new Array();
  16615. this.materials = new Array();
  16616. this.multiMaterials = new Array();
  16617. // Textures
  16618. this._texturesEnabled = true;
  16619. this.textures = new Array();
  16620. // Particles
  16621. this.particlesEnabled = true;
  16622. this.particleSystems = new Array();
  16623. // Sprites
  16624. this.spritesEnabled = true;
  16625. this.spriteManagers = new Array();
  16626. // Layers
  16627. this.layers = new Array();
  16628. this.highlightLayers = new Array();
  16629. // Skeletons
  16630. this._skeletonsEnabled = true;
  16631. this.skeletons = new Array();
  16632. // Morph targets
  16633. this.morphTargetManagers = new Array();
  16634. // Lens flares
  16635. this.lensFlaresEnabled = true;
  16636. this.lensFlareSystems = new Array();
  16637. // Collisions
  16638. this.collisionsEnabled = true;
  16639. /** Defines the gravity applied to this scene */
  16640. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16641. // Postprocesses
  16642. this.postProcesses = new Array();
  16643. this.postProcessesEnabled = true;
  16644. // Customs render targets
  16645. this.renderTargetsEnabled = true;
  16646. this.dumpNextRenderTargets = false;
  16647. this.customRenderTargets = new Array();
  16648. // Imported meshes
  16649. this.importedMeshesFiles = new Array();
  16650. // Probes
  16651. this.probesEnabled = true;
  16652. this.reflectionProbes = new Array();
  16653. this._actionManagers = new Array();
  16654. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16655. // Procedural textures
  16656. this.proceduralTexturesEnabled = true;
  16657. this._proceduralTextures = new Array();
  16658. this.soundTracks = new Array();
  16659. this._audioEnabled = true;
  16660. this._headphone = false;
  16661. // Performance counters
  16662. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16663. this._totalLightsCounter = new BABYLON.PerfCounter();
  16664. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16665. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16666. this._totalVertices = new BABYLON.PerfCounter();
  16667. this._activeIndices = new BABYLON.PerfCounter();
  16668. this._activeParticles = new BABYLON.PerfCounter();
  16669. this._interFrameDuration = new BABYLON.PerfCounter();
  16670. this._lastFrameDuration = new BABYLON.PerfCounter();
  16671. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16672. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16673. this._particlesDuration = new BABYLON.PerfCounter();
  16674. this._renderDuration = new BABYLON.PerfCounter();
  16675. this._spritesDuration = new BABYLON.PerfCounter();
  16676. this._activeBones = new BABYLON.PerfCounter();
  16677. this._animationTime = 0;
  16678. this.animationTimeScale = 1;
  16679. this._renderId = 0;
  16680. this._executeWhenReadyTimeoutId = -1;
  16681. this._intermediateRendering = false;
  16682. this._viewUpdateFlag = -1;
  16683. this._projectionUpdateFlag = -1;
  16684. this._alternateViewUpdateFlag = -1;
  16685. this._alternateProjectionUpdateFlag = -1;
  16686. this._toBeDisposed = new BABYLON.SmartArray(256);
  16687. this._pendingData = []; //ANY
  16688. this._activeMeshes = new BABYLON.SmartArray(256);
  16689. this._processedMaterials = new BABYLON.SmartArray(256);
  16690. this._renderTargets = new BABYLON.SmartArray(256);
  16691. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16692. this._activeSkeletons = new BABYLON.SmartArray(32);
  16693. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16694. this._activeAnimatables = new Array();
  16695. this._transformMatrix = BABYLON.Matrix.Zero();
  16696. this._useAlternateCameraConfiguration = false;
  16697. this._alternateRendering = false;
  16698. this.requireLightSorting = false;
  16699. this._uniqueIdCounter = 0;
  16700. this._activeMeshesFrozen = false;
  16701. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16702. this._engine.scenes.push(this);
  16703. this._uid = null;
  16704. this._renderingManager = new BABYLON.RenderingManager(this);
  16705. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16706. if (BABYLON.OutlineRenderer) {
  16707. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16708. }
  16709. this.attachControl();
  16710. if (BABYLON.SoundTrack) {
  16711. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16712. }
  16713. //simplification queue
  16714. if (BABYLON.SimplificationQueue) {
  16715. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16716. }
  16717. //collision coordinator initialization. For now legacy per default.
  16718. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16719. // Uniform Buffer
  16720. this._createUbo();
  16721. // Default Image processing definition.
  16722. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16723. }
  16724. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16725. /** The fog is deactivated */
  16726. get: function () {
  16727. return Scene._FOGMODE_NONE;
  16728. },
  16729. enumerable: true,
  16730. configurable: true
  16731. });
  16732. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16733. /** The fog density is following an exponential function */
  16734. get: function () {
  16735. return Scene._FOGMODE_EXP;
  16736. },
  16737. enumerable: true,
  16738. configurable: true
  16739. });
  16740. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16741. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16742. get: function () {
  16743. return Scene._FOGMODE_EXP2;
  16744. },
  16745. enumerable: true,
  16746. configurable: true
  16747. });
  16748. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16749. /** The fog density is following a linear function. */
  16750. get: function () {
  16751. return Scene._FOGMODE_LINEAR;
  16752. },
  16753. enumerable: true,
  16754. configurable: true
  16755. });
  16756. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16757. /**
  16758. * Texture used in all pbr material as the reflection texture.
  16759. * As in the majority of the scene they are the same (exception for multi room and so on),
  16760. * this is easier to reference from here than from all the materials.
  16761. */
  16762. get: function () {
  16763. return this._environmentTexture;
  16764. },
  16765. /**
  16766. * Texture used in all pbr material as the reflection texture.
  16767. * As in the majority of the scene they are the same (exception for multi room and so on),
  16768. * this is easier to set here than in all the materials.
  16769. */
  16770. set: function (value) {
  16771. this._environmentTexture = value;
  16772. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16778. /**
  16779. * Default image processing configuration used either in the rendering
  16780. * Forward main pass or through the imageProcessingPostProcess if present.
  16781. * As in the majority of the scene they are the same (exception for multi camera),
  16782. * this is easier to reference from here than from all the materials and post process.
  16783. *
  16784. * No setter as we it is a shared configuration, you can set the values instead.
  16785. */
  16786. get: function () {
  16787. return this._imageProcessingConfiguration;
  16788. },
  16789. enumerable: true,
  16790. configurable: true
  16791. });
  16792. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16793. get: function () {
  16794. return this._forcePointsCloud;
  16795. },
  16796. set: function (value) {
  16797. if (this._forcePointsCloud === value) {
  16798. return;
  16799. }
  16800. this._forcePointsCloud = value;
  16801. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(Scene.prototype, "onDispose", {
  16807. /** A function to be executed when this scene is disposed. */
  16808. set: function (callback) {
  16809. if (this._onDisposeObserver) {
  16810. this.onDisposeObservable.remove(this._onDisposeObserver);
  16811. }
  16812. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16813. },
  16814. enumerable: true,
  16815. configurable: true
  16816. });
  16817. Object.defineProperty(Scene.prototype, "beforeRender", {
  16818. /** A function to be executed before rendering this scene */
  16819. set: function (callback) {
  16820. if (this._onBeforeRenderObserver) {
  16821. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16822. }
  16823. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Object.defineProperty(Scene.prototype, "afterRender", {
  16829. /** A function to be executed after rendering this scene */
  16830. set: function (callback) {
  16831. if (this._onAfterRenderObserver) {
  16832. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16833. }
  16834. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16840. set: function (callback) {
  16841. if (this._onBeforeCameraRenderObserver) {
  16842. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16843. }
  16844. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16845. },
  16846. enumerable: true,
  16847. configurable: true
  16848. });
  16849. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16850. set: function (callback) {
  16851. if (this._onAfterCameraRenderObserver) {
  16852. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16853. }
  16854. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16860. get: function () {
  16861. if (!this._gamepadManager) {
  16862. this._gamepadManager = new BABYLON.GamepadManager();
  16863. }
  16864. return this._gamepadManager;
  16865. },
  16866. enumerable: true,
  16867. configurable: true
  16868. });
  16869. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16870. get: function () {
  16871. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16872. },
  16873. enumerable: true,
  16874. configurable: true
  16875. });
  16876. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16877. get: function () {
  16878. return this._useRightHandedSystem;
  16879. },
  16880. set: function (value) {
  16881. if (this._useRightHandedSystem === value) {
  16882. return;
  16883. }
  16884. this._useRightHandedSystem = value;
  16885. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16886. },
  16887. enumerable: true,
  16888. configurable: true
  16889. });
  16890. Scene.prototype.setStepId = function (newStepId) {
  16891. this._currentStepId = newStepId;
  16892. };
  16893. ;
  16894. Scene.prototype.getStepId = function () {
  16895. return this._currentStepId;
  16896. };
  16897. ;
  16898. Scene.prototype.getInternalStep = function () {
  16899. return this._currentInternalStep;
  16900. };
  16901. ;
  16902. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16903. get: function () {
  16904. return this._fogEnabled;
  16905. },
  16906. /**
  16907. * is fog enabled on this scene.
  16908. */
  16909. set: function (value) {
  16910. if (this._fogEnabled === value) {
  16911. return;
  16912. }
  16913. this._fogEnabled = value;
  16914. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Object.defineProperty(Scene.prototype, "fogMode", {
  16920. get: function () {
  16921. return this._fogMode;
  16922. },
  16923. set: function (value) {
  16924. if (this._fogMode === value) {
  16925. return;
  16926. }
  16927. this._fogMode = value;
  16928. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16929. },
  16930. enumerable: true,
  16931. configurable: true
  16932. });
  16933. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16934. get: function () {
  16935. return this._shadowsEnabled;
  16936. },
  16937. set: function (value) {
  16938. if (this._shadowsEnabled === value) {
  16939. return;
  16940. }
  16941. this._shadowsEnabled = value;
  16942. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16943. },
  16944. enumerable: true,
  16945. configurable: true
  16946. });
  16947. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16948. get: function () {
  16949. return this._lightsEnabled;
  16950. },
  16951. set: function (value) {
  16952. if (this._lightsEnabled === value) {
  16953. return;
  16954. }
  16955. this._lightsEnabled = value;
  16956. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16962. /** The default material used on meshes when no material is affected */
  16963. get: function () {
  16964. if (!this._defaultMaterial) {
  16965. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16966. }
  16967. return this._defaultMaterial;
  16968. },
  16969. /** The default material used on meshes when no material is affected */
  16970. set: function (value) {
  16971. this._defaultMaterial = value;
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16977. get: function () {
  16978. return this._texturesEnabled;
  16979. },
  16980. set: function (value) {
  16981. if (this._texturesEnabled === value) {
  16982. return;
  16983. }
  16984. this._texturesEnabled = value;
  16985. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16986. },
  16987. enumerable: true,
  16988. configurable: true
  16989. });
  16990. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16991. get: function () {
  16992. return this._skeletonsEnabled;
  16993. },
  16994. set: function (value) {
  16995. if (this._skeletonsEnabled === value) {
  16996. return;
  16997. }
  16998. this._skeletonsEnabled = value;
  16999. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17005. get: function () {
  17006. if (!this._postProcessRenderPipelineManager) {
  17007. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17008. }
  17009. return this._postProcessRenderPipelineManager;
  17010. },
  17011. enumerable: true,
  17012. configurable: true
  17013. });
  17014. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17015. get: function () {
  17016. return this._alternateRendering;
  17017. },
  17018. enumerable: true,
  17019. configurable: true
  17020. });
  17021. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17022. get: function () {
  17023. return this._frustumPlanes;
  17024. },
  17025. enumerable: true,
  17026. configurable: true
  17027. });
  17028. Object.defineProperty(Scene.prototype, "debugLayer", {
  17029. // Properties
  17030. get: function () {
  17031. if (!this._debugLayer) {
  17032. this._debugLayer = new BABYLON.DebugLayer(this);
  17033. }
  17034. return this._debugLayer;
  17035. },
  17036. enumerable: true,
  17037. configurable: true
  17038. });
  17039. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17040. get: function () {
  17041. return this._workerCollisions;
  17042. },
  17043. set: function (enabled) {
  17044. if (!BABYLON.CollisionCoordinatorLegacy) {
  17045. return;
  17046. }
  17047. enabled = (enabled && !!Worker);
  17048. this._workerCollisions = enabled;
  17049. if (this.collisionCoordinator) {
  17050. this.collisionCoordinator.destroy();
  17051. }
  17052. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17053. this.collisionCoordinator.init(this);
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17059. get: function () {
  17060. return this._selectionOctree;
  17061. },
  17062. enumerable: true,
  17063. configurable: true
  17064. });
  17065. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17066. /**
  17067. * The mesh that is currently under the pointer.
  17068. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17069. */
  17070. get: function () {
  17071. return this._pointerOverMesh;
  17072. },
  17073. enumerable: true,
  17074. configurable: true
  17075. });
  17076. Object.defineProperty(Scene.prototype, "pointerX", {
  17077. /**
  17078. * Current on-screen X position of the pointer
  17079. * @return {number} X position of the pointer
  17080. */
  17081. get: function () {
  17082. return this._pointerX;
  17083. },
  17084. enumerable: true,
  17085. configurable: true
  17086. });
  17087. Object.defineProperty(Scene.prototype, "pointerY", {
  17088. /**
  17089. * Current on-screen Y position of the pointer
  17090. * @return {number} Y position of the pointer
  17091. */
  17092. get: function () {
  17093. return this._pointerY;
  17094. },
  17095. enumerable: true,
  17096. configurable: true
  17097. });
  17098. Scene.prototype.getCachedMaterial = function () {
  17099. return this._cachedMaterial;
  17100. };
  17101. Scene.prototype.getCachedEffect = function () {
  17102. return this._cachedEffect;
  17103. };
  17104. Scene.prototype.getCachedVisibility = function () {
  17105. return this._cachedVisibility;
  17106. };
  17107. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17108. if (visibility === void 0) { visibility = 1; }
  17109. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17110. };
  17111. Scene.prototype.getBoundingBoxRenderer = function () {
  17112. if (!this._boundingBoxRenderer) {
  17113. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17114. }
  17115. return this._boundingBoxRenderer;
  17116. };
  17117. Scene.prototype.getOutlineRenderer = function () {
  17118. return this._outlineRenderer;
  17119. };
  17120. Scene.prototype.getEngine = function () {
  17121. return this._engine;
  17122. };
  17123. Scene.prototype.getTotalVertices = function () {
  17124. return this._totalVertices.current;
  17125. };
  17126. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17127. get: function () {
  17128. return this._totalVertices;
  17129. },
  17130. enumerable: true,
  17131. configurable: true
  17132. });
  17133. Scene.prototype.getActiveIndices = function () {
  17134. return this._activeIndices.current;
  17135. };
  17136. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17137. get: function () {
  17138. return this._activeIndices;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. Scene.prototype.getActiveParticles = function () {
  17144. return this._activeParticles.current;
  17145. };
  17146. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17147. get: function () {
  17148. return this._activeParticles;
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Scene.prototype.getActiveBones = function () {
  17154. return this._activeBones.current;
  17155. };
  17156. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17157. get: function () {
  17158. return this._activeBones;
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. // Stats
  17164. Scene.prototype.getInterFramePerfCounter = function () {
  17165. return this._interFrameDuration.current;
  17166. };
  17167. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17168. get: function () {
  17169. return this._interFrameDuration;
  17170. },
  17171. enumerable: true,
  17172. configurable: true
  17173. });
  17174. Scene.prototype.getLastFrameDuration = function () {
  17175. return this._lastFrameDuration.current;
  17176. };
  17177. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17178. get: function () {
  17179. return this._lastFrameDuration;
  17180. },
  17181. enumerable: true,
  17182. configurable: true
  17183. });
  17184. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17185. return this._evaluateActiveMeshesDuration.current;
  17186. };
  17187. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17188. get: function () {
  17189. return this._evaluateActiveMeshesDuration;
  17190. },
  17191. enumerable: true,
  17192. configurable: true
  17193. });
  17194. Scene.prototype.getActiveMeshes = function () {
  17195. return this._activeMeshes;
  17196. };
  17197. Scene.prototype.getRenderTargetsDuration = function () {
  17198. return this._renderTargetsDuration.current;
  17199. };
  17200. Scene.prototype.getRenderDuration = function () {
  17201. return this._renderDuration.current;
  17202. };
  17203. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17204. get: function () {
  17205. return this._renderDuration;
  17206. },
  17207. enumerable: true,
  17208. configurable: true
  17209. });
  17210. Scene.prototype.getParticlesDuration = function () {
  17211. return this._particlesDuration.current;
  17212. };
  17213. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17214. get: function () {
  17215. return this._particlesDuration;
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. Scene.prototype.getSpritesDuration = function () {
  17221. return this._spritesDuration.current;
  17222. };
  17223. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17224. get: function () {
  17225. return this._spritesDuration;
  17226. },
  17227. enumerable: true,
  17228. configurable: true
  17229. });
  17230. Scene.prototype.getAnimationRatio = function () {
  17231. return this._animationRatio;
  17232. };
  17233. Scene.prototype.getRenderId = function () {
  17234. return this._renderId;
  17235. };
  17236. Scene.prototype.incrementRenderId = function () {
  17237. this._renderId++;
  17238. };
  17239. Scene.prototype._updatePointerPosition = function (evt) {
  17240. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17241. this._pointerX = evt.clientX - canvasRect.left;
  17242. this._pointerY = evt.clientY - canvasRect.top;
  17243. this._unTranslatedPointerX = this._pointerX;
  17244. this._unTranslatedPointerY = this._pointerY;
  17245. };
  17246. Scene.prototype._createUbo = function () {
  17247. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17248. this._sceneUbo.addUniform("viewProjection", 16);
  17249. this._sceneUbo.addUniform("view", 16);
  17250. };
  17251. Scene.prototype._createAlternateUbo = function () {
  17252. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17253. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17254. this._alternateSceneUbo.addUniform("view", 16);
  17255. };
  17256. // Pointers handling
  17257. /**
  17258. * Use this method to simulate a pointer move on a mesh
  17259. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17260. */
  17261. Scene.prototype.simulatePointerMove = function (pickResult) {
  17262. var evt = new PointerEvent("pointermove");
  17263. return this._processPointerMove(pickResult, evt);
  17264. };
  17265. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17266. var canvas = this._engine.getRenderingCanvas();
  17267. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17268. this.setPointerOverSprite(null);
  17269. this.setPointerOverMesh(pickResult.pickedMesh);
  17270. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17271. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17272. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17273. }
  17274. else {
  17275. canvas.style.cursor = this.hoverCursor;
  17276. }
  17277. }
  17278. else {
  17279. canvas.style.cursor = this.defaultCursor;
  17280. }
  17281. }
  17282. else {
  17283. this.setPointerOverMesh(null);
  17284. // Sprites
  17285. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17286. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17287. this.setPointerOverSprite(pickResult.pickedSprite);
  17288. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17289. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17290. }
  17291. else {
  17292. canvas.style.cursor = this.hoverCursor;
  17293. }
  17294. }
  17295. else {
  17296. this.setPointerOverSprite(null);
  17297. // Restore pointer
  17298. canvas.style.cursor = this.defaultCursor;
  17299. }
  17300. }
  17301. if (this.onPointerMove) {
  17302. this.onPointerMove(evt, pickResult);
  17303. }
  17304. if (this.onPointerObservable.hasObservers()) {
  17305. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17306. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17307. this.onPointerObservable.notifyObservers(pi, type);
  17308. }
  17309. return this;
  17310. };
  17311. /**
  17312. * Use this method to simulate a pointer down on a mesh
  17313. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17314. */
  17315. Scene.prototype.simulatePointerDown = function (pickResult) {
  17316. var evt = new PointerEvent("pointerdown");
  17317. return this._processPointerDown(pickResult, evt);
  17318. };
  17319. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17320. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17321. this._pickedDownMesh = pickResult.pickedMesh;
  17322. var actionManager = pickResult.pickedMesh.actionManager;
  17323. if (actionManager) {
  17324. if (actionManager.hasPickTriggers) {
  17325. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17326. switch (evt.button) {
  17327. case 0:
  17328. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17329. break;
  17330. case 1:
  17331. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17332. break;
  17333. case 2:
  17334. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17335. break;
  17336. }
  17337. }
  17338. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17339. window.setTimeout((function () {
  17340. var _this = this;
  17341. 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);
  17342. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17343. if (this._isButtonPressed &&
  17344. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17345. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17346. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17347. this._startingPointerTime = 0;
  17348. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17349. }
  17350. }
  17351. }).bind(this), Scene.LongPressDelay);
  17352. }
  17353. }
  17354. }
  17355. if (this.onPointerDown) {
  17356. this.onPointerDown(evt, pickResult);
  17357. }
  17358. if (this.onPointerObservable.hasObservers()) {
  17359. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17360. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17361. this.onPointerObservable.notifyObservers(pi, type);
  17362. }
  17363. return this;
  17364. };
  17365. /**
  17366. * Use this method to simulate a pointer up on a mesh
  17367. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17368. */
  17369. Scene.prototype.simulatePointerUp = function (pickResult) {
  17370. var evt = new PointerEvent("pointerup");
  17371. var clickInfo = new ClickInfo();
  17372. clickInfo.singleClick = true;
  17373. return this._processPointerUp(pickResult, evt, clickInfo);
  17374. };
  17375. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17376. if (pickResult && pickResult && pickResult.pickedMesh) {
  17377. this._pickedUpMesh = pickResult.pickedMesh;
  17378. if (this._pickedDownMesh === this._pickedUpMesh) {
  17379. if (this.onPointerPick) {
  17380. this.onPointerPick(evt, pickResult);
  17381. }
  17382. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17383. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17384. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17385. this.onPointerObservable.notifyObservers(pi, type);
  17386. }
  17387. }
  17388. if (pickResult.pickedMesh.actionManager) {
  17389. if (clickInfo.ignore) {
  17390. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17391. }
  17392. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17393. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17394. }
  17395. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17396. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17397. }
  17398. }
  17399. }
  17400. if (this._pickedDownMesh &&
  17401. this._pickedDownMesh.actionManager &&
  17402. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17403. this._pickedDownMesh !== this._pickedUpMesh) {
  17404. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17405. }
  17406. if (this.onPointerUp) {
  17407. this.onPointerUp(evt, pickResult);
  17408. }
  17409. if (this.onPointerObservable.hasObservers()) {
  17410. if (!clickInfo.ignore) {
  17411. if (!clickInfo.hasSwiped) {
  17412. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17413. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17414. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17415. this.onPointerObservable.notifyObservers(pi, type);
  17416. }
  17417. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17418. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17419. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17420. this.onPointerObservable.notifyObservers(pi, type);
  17421. }
  17422. }
  17423. }
  17424. else {
  17425. var type = BABYLON.PointerEventTypes.POINTERUP;
  17426. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17427. this.onPointerObservable.notifyObservers(pi, type);
  17428. }
  17429. }
  17430. return this;
  17431. };
  17432. /**
  17433. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17434. * @param attachUp defines if you want to attach events to pointerup
  17435. * @param attachDown defines if you want to attach events to pointerdown
  17436. * @param attachMove defines if you want to attach events to pointermove
  17437. */
  17438. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17439. var _this = this;
  17440. if (attachUp === void 0) { attachUp = true; }
  17441. if (attachDown === void 0) { attachDown = true; }
  17442. if (attachMove === void 0) { attachMove = true; }
  17443. this._initActionManager = function (act, clickInfo) {
  17444. if (!_this._meshPickProceed) {
  17445. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17446. _this._currentPickResult = pickResult;
  17447. if (pickResult) {
  17448. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17449. }
  17450. _this._meshPickProceed = true;
  17451. }
  17452. return act;
  17453. };
  17454. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17455. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17456. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17457. btn !== _this._previousButtonPressed) {
  17458. _this._doubleClickOccured = false;
  17459. clickInfo.singleClick = true;
  17460. clickInfo.ignore = false;
  17461. cb(clickInfo, _this._currentPickResult);
  17462. }
  17463. };
  17464. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17465. var clickInfo = new ClickInfo();
  17466. _this._currentPickResult = null;
  17467. var act;
  17468. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17469. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17470. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17471. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17472. act = _this._initActionManager(act, clickInfo);
  17473. if (act)
  17474. checkPicking = act.hasPickTriggers;
  17475. }
  17476. if (checkPicking) {
  17477. var btn = evt.button;
  17478. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17479. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17480. if (!clickInfo.hasSwiped) {
  17481. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17482. if (!checkSingleClickImmediately) {
  17483. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17484. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17485. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17486. act = _this._initActionManager(act, clickInfo);
  17487. if (act)
  17488. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17489. }
  17490. }
  17491. if (checkSingleClickImmediately) {
  17492. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17493. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17494. btn !== _this._previousButtonPressed) {
  17495. clickInfo.singleClick = true;
  17496. cb(clickInfo, _this._currentPickResult);
  17497. }
  17498. }
  17499. else {
  17500. // wait that no double click has been raised during the double click delay
  17501. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17502. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17503. }
  17504. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17505. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17506. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17507. act = _this._initActionManager(act, clickInfo);
  17508. if (act)
  17509. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17510. }
  17511. if (checkDoubleClick) {
  17512. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17513. if (btn === _this._previousButtonPressed &&
  17514. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17515. !_this._doubleClickOccured) {
  17516. // pointer has not moved for 2 clicks, it's a double click
  17517. if (!clickInfo.hasSwiped &&
  17518. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17519. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17520. _this._previousStartingPointerTime = 0;
  17521. _this._doubleClickOccured = true;
  17522. clickInfo.doubleClick = true;
  17523. clickInfo.ignore = false;
  17524. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17525. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17526. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17527. cb(clickInfo, _this._currentPickResult);
  17528. }
  17529. else {
  17530. _this._doubleClickOccured = false;
  17531. _this._previousStartingPointerTime = _this._startingPointerTime;
  17532. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17533. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17534. _this._previousButtonPressed = btn;
  17535. _this._previousHasSwiped = clickInfo.hasSwiped;
  17536. if (Scene.ExclusiveDoubleClickMode) {
  17537. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17538. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17539. }
  17540. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17541. cb(clickInfo, _this._previousPickResult);
  17542. }
  17543. else {
  17544. cb(clickInfo, _this._currentPickResult);
  17545. }
  17546. }
  17547. }
  17548. else {
  17549. _this._doubleClickOccured = false;
  17550. _this._previousStartingPointerTime = _this._startingPointerTime;
  17551. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17552. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17553. _this._previousButtonPressed = btn;
  17554. _this._previousHasSwiped = clickInfo.hasSwiped;
  17555. }
  17556. }
  17557. }
  17558. }
  17559. clickInfo.ignore = true;
  17560. cb(clickInfo, _this._currentPickResult);
  17561. };
  17562. this._spritePredicate = function (sprite) {
  17563. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17564. };
  17565. this._onPointerMove = function (evt) {
  17566. _this._updatePointerPosition(evt);
  17567. // PreObservable support
  17568. if (_this.onPrePointerObservable.hasObservers()) {
  17569. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17570. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17571. _this.onPrePointerObservable.notifyObservers(pi, type);
  17572. if (pi.skipOnPointerObservable) {
  17573. return;
  17574. }
  17575. }
  17576. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17577. return;
  17578. }
  17579. if (!_this.pointerMovePredicate) {
  17580. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17581. }
  17582. // Meshes
  17583. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17584. _this._processPointerMove(pickResult, evt);
  17585. };
  17586. this._onPointerDown = function (evt) {
  17587. _this._isButtonPressed = true;
  17588. _this._pickedDownMesh = null;
  17589. _this._meshPickProceed = false;
  17590. _this._updatePointerPosition(evt);
  17591. // PreObservable support
  17592. if (_this.onPrePointerObservable.hasObservers()) {
  17593. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17594. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17595. _this.onPrePointerObservable.notifyObservers(pi, type);
  17596. if (pi.skipOnPointerObservable) {
  17597. return;
  17598. }
  17599. }
  17600. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17601. return;
  17602. }
  17603. _this._startingPointerPosition.x = _this._pointerX;
  17604. _this._startingPointerPosition.y = _this._pointerY;
  17605. _this._startingPointerTime = new Date().getTime();
  17606. if (!_this.pointerDownPredicate) {
  17607. _this.pointerDownPredicate = function (mesh) {
  17608. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17609. };
  17610. }
  17611. // Meshes
  17612. _this._pickedDownMesh = null;
  17613. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17614. _this._processPointerDown(pickResult, evt);
  17615. // Sprites
  17616. _this._pickedDownSprite = null;
  17617. if (_this.spriteManagers.length > 0) {
  17618. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17619. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17620. if (pickResult.pickedSprite.actionManager) {
  17621. _this._pickedDownSprite = pickResult.pickedSprite;
  17622. switch (evt.button) {
  17623. case 0:
  17624. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17625. break;
  17626. case 1:
  17627. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17628. break;
  17629. case 2:
  17630. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17631. break;
  17632. }
  17633. if (pickResult.pickedSprite.actionManager) {
  17634. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17635. }
  17636. }
  17637. }
  17638. }
  17639. };
  17640. this._onPointerUp = function (evt) {
  17641. _this._isButtonPressed = false;
  17642. _this._pickedUpMesh = null;
  17643. _this._meshPickProceed = false;
  17644. _this._updatePointerPosition(evt);
  17645. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17646. // PreObservable support
  17647. if (this.onPrePointerObservable.hasObservers()) {
  17648. if (!clickInfo.ignore) {
  17649. if (!clickInfo.hasSwiped) {
  17650. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17651. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17652. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17653. this.onPrePointerObservable.notifyObservers(pi, type);
  17654. if (pi.skipOnPointerObservable) {
  17655. return;
  17656. }
  17657. }
  17658. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17659. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17660. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17661. this.onPrePointerObservable.notifyObservers(pi, type);
  17662. if (pi.skipOnPointerObservable) {
  17663. return;
  17664. }
  17665. }
  17666. }
  17667. }
  17668. else {
  17669. var type = BABYLON.PointerEventTypes.POINTERUP;
  17670. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17671. this.onPrePointerObservable.notifyObservers(pi, type);
  17672. if (pi.skipOnPointerObservable) {
  17673. return;
  17674. }
  17675. }
  17676. }
  17677. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17678. return;
  17679. }
  17680. if (!this.pointerUpPredicate) {
  17681. this.pointerUpPredicate = function (mesh) {
  17682. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17683. };
  17684. }
  17685. // Meshes
  17686. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17687. this._initActionManager(null, clickInfo);
  17688. }
  17689. if (!pickResult) {
  17690. pickResult = this._currentPickResult;
  17691. }
  17692. this._processPointerUp(pickResult, evt, clickInfo);
  17693. // Sprites
  17694. if (this.spriteManagers.length > 0) {
  17695. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17696. if (pickResult.hit && pickResult.pickedSprite) {
  17697. if (pickResult.pickedSprite.actionManager) {
  17698. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17699. if (pickResult.pickedSprite.actionManager) {
  17700. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17701. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17702. }
  17703. }
  17704. }
  17705. }
  17706. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17707. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17708. }
  17709. }
  17710. this._previousPickResult = this._currentPickResult;
  17711. }).bind(_this));
  17712. };
  17713. this._onKeyDown = function (evt) {
  17714. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17715. if (_this.onPreKeyboardObservable.hasObservers()) {
  17716. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17717. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17718. if (pi.skipOnPointerObservable) {
  17719. return;
  17720. }
  17721. }
  17722. if (_this.onKeyboardObservable.hasObservers()) {
  17723. var pi = new BABYLON.KeyboardInfo(type, evt);
  17724. _this.onKeyboardObservable.notifyObservers(pi, type);
  17725. }
  17726. if (_this.actionManager) {
  17727. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17728. }
  17729. };
  17730. this._onKeyUp = function (evt) {
  17731. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17732. if (_this.onPreKeyboardObservable.hasObservers()) {
  17733. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17734. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17735. if (pi.skipOnPointerObservable) {
  17736. return;
  17737. }
  17738. }
  17739. if (_this.onKeyboardObservable.hasObservers()) {
  17740. var pi = new BABYLON.KeyboardInfo(type, evt);
  17741. _this.onKeyboardObservable.notifyObservers(pi, type);
  17742. }
  17743. if (_this.actionManager) {
  17744. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17745. }
  17746. };
  17747. var engine = this.getEngine();
  17748. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17749. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17750. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17751. });
  17752. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17753. canvas.removeEventListener("keydown", _this._onKeyDown);
  17754. canvas.removeEventListener("keyup", _this._onKeyUp);
  17755. });
  17756. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17757. var canvas = this._engine.getRenderingCanvas();
  17758. if (attachMove) {
  17759. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17760. // Wheel
  17761. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17762. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17763. }
  17764. if (attachDown) {
  17765. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17766. }
  17767. if (attachUp) {
  17768. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17769. }
  17770. canvas.tabIndex = 1;
  17771. };
  17772. Scene.prototype.detachControl = function () {
  17773. var engine = this.getEngine();
  17774. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17775. var canvas = engine.getRenderingCanvas();
  17776. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17777. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17778. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17779. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17780. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17781. // Wheel
  17782. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17783. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17784. // Keyboard
  17785. canvas.removeEventListener("keydown", this._onKeyDown);
  17786. canvas.removeEventListener("keyup", this._onKeyUp);
  17787. // Observables
  17788. this.onKeyboardObservable.clear();
  17789. this.onPreKeyboardObservable.clear();
  17790. this.onPointerObservable.clear();
  17791. this.onPrePointerObservable.clear();
  17792. };
  17793. // Ready
  17794. Scene.prototype.isReady = function () {
  17795. if (this._pendingData.length > 0) {
  17796. return false;
  17797. }
  17798. var index;
  17799. // Geometries
  17800. for (index = 0; index < this._geometries.length; index++) {
  17801. var geometry = this._geometries[index];
  17802. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17803. return false;
  17804. }
  17805. }
  17806. // Meshes
  17807. for (index = 0; index < this.meshes.length; index++) {
  17808. var mesh = this.meshes[index];
  17809. if (!mesh.isEnabled()) {
  17810. continue;
  17811. }
  17812. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17813. continue;
  17814. }
  17815. if (!mesh.isReady()) {
  17816. return false;
  17817. }
  17818. var mat = mesh.material;
  17819. if (mat) {
  17820. if (!mat.isReady(mesh)) {
  17821. return false;
  17822. }
  17823. }
  17824. }
  17825. return true;
  17826. };
  17827. Scene.prototype.resetCachedMaterial = function () {
  17828. this._cachedMaterial = null;
  17829. this._cachedEffect = null;
  17830. this._cachedVisibility = null;
  17831. };
  17832. Scene.prototype.registerBeforeRender = function (func) {
  17833. this.onBeforeRenderObservable.add(func);
  17834. };
  17835. Scene.prototype.unregisterBeforeRender = function (func) {
  17836. this.onBeforeRenderObservable.removeCallback(func);
  17837. };
  17838. Scene.prototype.registerAfterRender = function (func) {
  17839. this.onAfterRenderObservable.add(func);
  17840. };
  17841. Scene.prototype.unregisterAfterRender = function (func) {
  17842. this.onAfterRenderObservable.removeCallback(func);
  17843. };
  17844. Scene.prototype._addPendingData = function (data) {
  17845. this._pendingData.push(data);
  17846. };
  17847. Scene.prototype._removePendingData = function (data) {
  17848. var index = this._pendingData.indexOf(data);
  17849. if (index !== -1) {
  17850. this._pendingData.splice(index, 1);
  17851. }
  17852. };
  17853. Scene.prototype.getWaitingItemsCount = function () {
  17854. return this._pendingData.length;
  17855. };
  17856. /**
  17857. * Registers a function to be executed when the scene is ready.
  17858. * @param {Function} func - the function to be executed.
  17859. */
  17860. Scene.prototype.executeWhenReady = function (func) {
  17861. var _this = this;
  17862. this.onReadyObservable.add(func);
  17863. if (this._executeWhenReadyTimeoutId !== -1) {
  17864. return;
  17865. }
  17866. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17867. _this._checkIsReady();
  17868. }, 150);
  17869. };
  17870. Scene.prototype._checkIsReady = function () {
  17871. var _this = this;
  17872. if (this.isReady()) {
  17873. this.onReadyObservable.notifyObservers(this);
  17874. this.onReadyObservable.clear();
  17875. this._executeWhenReadyTimeoutId = -1;
  17876. return;
  17877. }
  17878. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17879. _this._checkIsReady();
  17880. }, 150);
  17881. };
  17882. // Animations
  17883. /**
  17884. * Will start the animation sequence of a given target
  17885. * @param target - the target
  17886. * @param {number} from - from which frame should animation start
  17887. * @param {number} to - till which frame should animation run.
  17888. * @param {boolean} [loop] - should the animation loop
  17889. * @param {number} [speedRatio] - the speed in which to run the animation
  17890. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17891. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17892. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17893. * See BABYLON.Animatable
  17894. */
  17895. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17896. if (speedRatio === void 0) { speedRatio = 1.0; }
  17897. if (from > to && speedRatio > 0) {
  17898. speedRatio *= -1;
  17899. }
  17900. this.stopAnimation(target);
  17901. if (!animatable) {
  17902. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17903. }
  17904. // Local animations
  17905. if (target.animations) {
  17906. animatable.appendAnimations(target, target.animations);
  17907. }
  17908. // Children animations
  17909. if (target.getAnimatables) {
  17910. var animatables = target.getAnimatables();
  17911. for (var index = 0; index < animatables.length; index++) {
  17912. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17913. }
  17914. }
  17915. animatable.reset();
  17916. return animatable;
  17917. };
  17918. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17919. if (speedRatio === undefined) {
  17920. speedRatio = 1.0;
  17921. }
  17922. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17923. return animatable;
  17924. };
  17925. Scene.prototype.getAnimatableByTarget = function (target) {
  17926. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17927. if (this._activeAnimatables[index].target === target) {
  17928. return this._activeAnimatables[index];
  17929. }
  17930. }
  17931. return null;
  17932. };
  17933. Object.defineProperty(Scene.prototype, "Animatables", {
  17934. get: function () {
  17935. return this._activeAnimatables;
  17936. },
  17937. enumerable: true,
  17938. configurable: true
  17939. });
  17940. /**
  17941. * Will stop the animation of the given target
  17942. * @param target - the target
  17943. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17944. * @see beginAnimation
  17945. */
  17946. Scene.prototype.stopAnimation = function (target, animationName) {
  17947. var animatable = this.getAnimatableByTarget(target);
  17948. if (animatable) {
  17949. animatable.stop(animationName);
  17950. }
  17951. };
  17952. Scene.prototype._animate = function () {
  17953. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17954. return;
  17955. }
  17956. // Getting time
  17957. var now = BABYLON.Tools.Now;
  17958. if (!this._animationTimeLast) {
  17959. if (this._pendingData.length > 0) {
  17960. return;
  17961. }
  17962. this._animationTimeLast = now;
  17963. }
  17964. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17965. this._animationTime += deltaTime;
  17966. this._animationTimeLast = now;
  17967. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17968. this._activeAnimatables[index]._animate(this._animationTime);
  17969. }
  17970. };
  17971. // Matrix
  17972. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  17973. this._useAlternateCameraConfiguration = active;
  17974. };
  17975. Scene.prototype.getViewMatrix = function () {
  17976. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  17977. };
  17978. Scene.prototype.getProjectionMatrix = function () {
  17979. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  17980. };
  17981. Scene.prototype.getTransformMatrix = function () {
  17982. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  17983. };
  17984. Scene.prototype.setTransformMatrix = function (view, projection) {
  17985. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17986. return;
  17987. }
  17988. this._viewUpdateFlag = view.updateFlag;
  17989. this._projectionUpdateFlag = projection.updateFlag;
  17990. this._viewMatrix = view;
  17991. this._projectionMatrix = projection;
  17992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17993. // Update frustum
  17994. if (!this._frustumPlanes) {
  17995. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17996. }
  17997. else {
  17998. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17999. }
  18000. if (this._sceneUbo.useUbo) {
  18001. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18002. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18003. this._sceneUbo.update();
  18004. }
  18005. };
  18006. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18007. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18008. return;
  18009. }
  18010. this._alternateViewUpdateFlag = view.updateFlag;
  18011. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18012. this._alternateViewMatrix = view;
  18013. this._alternateProjectionMatrix = projection;
  18014. if (!this._alternateTransformMatrix) {
  18015. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18016. }
  18017. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18018. if (!this._alternateSceneUbo) {
  18019. this._createAlternateUbo();
  18020. }
  18021. if (this._alternateSceneUbo.useUbo) {
  18022. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18023. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18024. this._alternateSceneUbo.update();
  18025. }
  18026. };
  18027. Scene.prototype.getSceneUniformBuffer = function () {
  18028. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18029. };
  18030. // Methods
  18031. Scene.prototype.getUniqueId = function () {
  18032. var result = this._uniqueIdCounter;
  18033. this._uniqueIdCounter++;
  18034. return result;
  18035. };
  18036. Scene.prototype.addMesh = function (newMesh) {
  18037. newMesh.uniqueId = this.getUniqueId();
  18038. var position = this.meshes.push(newMesh);
  18039. //notify the collision coordinator
  18040. if (this.collisionCoordinator) {
  18041. this.collisionCoordinator.onMeshAdded(newMesh);
  18042. }
  18043. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18044. };
  18045. Scene.prototype.removeMesh = function (toRemove) {
  18046. var index = this.meshes.indexOf(toRemove);
  18047. if (index !== -1) {
  18048. // Remove from the scene if mesh found
  18049. this.meshes.splice(index, 1);
  18050. }
  18051. //notify the collision coordinator
  18052. if (this.collisionCoordinator) {
  18053. this.collisionCoordinator.onMeshRemoved(toRemove);
  18054. }
  18055. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18056. return index;
  18057. };
  18058. Scene.prototype.removeSkeleton = function (toRemove) {
  18059. var index = this.skeletons.indexOf(toRemove);
  18060. if (index !== -1) {
  18061. // Remove from the scene if found
  18062. this.skeletons.splice(index, 1);
  18063. }
  18064. return index;
  18065. };
  18066. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18067. var index = this.morphTargetManagers.indexOf(toRemove);
  18068. if (index !== -1) {
  18069. // Remove from the scene if found
  18070. this.morphTargetManagers.splice(index, 1);
  18071. }
  18072. return index;
  18073. };
  18074. Scene.prototype.removeLight = function (toRemove) {
  18075. var index = this.lights.indexOf(toRemove);
  18076. if (index !== -1) {
  18077. // Remove from the scene if mesh found
  18078. this.lights.splice(index, 1);
  18079. this.sortLightsByPriority();
  18080. }
  18081. this.onLightRemovedObservable.notifyObservers(toRemove);
  18082. return index;
  18083. };
  18084. Scene.prototype.removeCamera = function (toRemove) {
  18085. var index = this.cameras.indexOf(toRemove);
  18086. if (index !== -1) {
  18087. // Remove from the scene if mesh found
  18088. this.cameras.splice(index, 1);
  18089. }
  18090. // Remove from activeCameras
  18091. var index2 = this.activeCameras.indexOf(toRemove);
  18092. if (index2 !== -1) {
  18093. // Remove from the scene if mesh found
  18094. this.activeCameras.splice(index2, 1);
  18095. }
  18096. // Reset the activeCamera
  18097. if (this.activeCamera === toRemove) {
  18098. if (this.cameras.length > 0) {
  18099. this.activeCamera = this.cameras[0];
  18100. }
  18101. else {
  18102. this.activeCamera = null;
  18103. }
  18104. }
  18105. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18106. return index;
  18107. };
  18108. Scene.prototype.addLight = function (newLight) {
  18109. newLight.uniqueId = this.getUniqueId();
  18110. this.lights.push(newLight);
  18111. this.sortLightsByPriority();
  18112. this.onNewLightAddedObservable.notifyObservers(newLight);
  18113. };
  18114. Scene.prototype.sortLightsByPriority = function () {
  18115. if (this.requireLightSorting) {
  18116. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18117. }
  18118. };
  18119. Scene.prototype.addCamera = function (newCamera) {
  18120. newCamera.uniqueId = this.getUniqueId();
  18121. var position = this.cameras.push(newCamera);
  18122. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18123. };
  18124. /**
  18125. * Switch active camera
  18126. * @param {Camera} newCamera - new active camera
  18127. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18128. */
  18129. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18130. if (attachControl === void 0) { attachControl = true; }
  18131. var canvas = this._engine.getRenderingCanvas();
  18132. this.activeCamera.detachControl(canvas);
  18133. this.activeCamera = newCamera;
  18134. if (attachControl) {
  18135. newCamera.attachControl(canvas);
  18136. }
  18137. };
  18138. /**
  18139. * sets the active camera of the scene using its ID
  18140. * @param {string} id - the camera's ID
  18141. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18142. * @see activeCamera
  18143. */
  18144. Scene.prototype.setActiveCameraByID = function (id) {
  18145. var camera = this.getCameraByID(id);
  18146. if (camera) {
  18147. this.activeCamera = camera;
  18148. return camera;
  18149. }
  18150. return null;
  18151. };
  18152. /**
  18153. * sets the active camera of the scene using its name
  18154. * @param {string} name - the camera's name
  18155. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18156. * @see activeCamera
  18157. */
  18158. Scene.prototype.setActiveCameraByName = function (name) {
  18159. var camera = this.getCameraByName(name);
  18160. if (camera) {
  18161. this.activeCamera = camera;
  18162. return camera;
  18163. }
  18164. return null;
  18165. };
  18166. /**
  18167. * get a material using its id
  18168. * @param {string} the material's ID
  18169. * @return {BABYLON.Material|null} the material or null if none found.
  18170. */
  18171. Scene.prototype.getMaterialByID = function (id) {
  18172. for (var index = 0; index < this.materials.length; index++) {
  18173. if (this.materials[index].id === id) {
  18174. return this.materials[index];
  18175. }
  18176. }
  18177. return null;
  18178. };
  18179. /**
  18180. * get a material using its name
  18181. * @param {string} the material's name
  18182. * @return {BABYLON.Material|null} the material or null if none found.
  18183. */
  18184. Scene.prototype.getMaterialByName = function (name) {
  18185. for (var index = 0; index < this.materials.length; index++) {
  18186. if (this.materials[index].name === name) {
  18187. return this.materials[index];
  18188. }
  18189. }
  18190. return null;
  18191. };
  18192. Scene.prototype.getLensFlareSystemByName = function (name) {
  18193. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18194. if (this.lensFlareSystems[index].name === name) {
  18195. return this.lensFlareSystems[index];
  18196. }
  18197. }
  18198. return null;
  18199. };
  18200. Scene.prototype.getLensFlareSystemByID = function (id) {
  18201. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18202. if (this.lensFlareSystems[index].id === id) {
  18203. return this.lensFlareSystems[index];
  18204. }
  18205. }
  18206. return null;
  18207. };
  18208. Scene.prototype.getCameraByID = function (id) {
  18209. for (var index = 0; index < this.cameras.length; index++) {
  18210. if (this.cameras[index].id === id) {
  18211. return this.cameras[index];
  18212. }
  18213. }
  18214. return null;
  18215. };
  18216. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18217. for (var index = 0; index < this.cameras.length; index++) {
  18218. if (this.cameras[index].uniqueId === uniqueId) {
  18219. return this.cameras[index];
  18220. }
  18221. }
  18222. return null;
  18223. };
  18224. /**
  18225. * get a camera using its name
  18226. * @param {string} the camera's name
  18227. * @return {BABYLON.Camera|null} the camera or null if none found.
  18228. */
  18229. Scene.prototype.getCameraByName = function (name) {
  18230. for (var index = 0; index < this.cameras.length; index++) {
  18231. if (this.cameras[index].name === name) {
  18232. return this.cameras[index];
  18233. }
  18234. }
  18235. return null;
  18236. };
  18237. /**
  18238. * get a bone using its id
  18239. * @param {string} the bone's id
  18240. * @return {BABYLON.Bone|null} the bone or null if not found
  18241. */
  18242. Scene.prototype.getBoneByID = function (id) {
  18243. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18244. var skeleton = this.skeletons[skeletonIndex];
  18245. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18246. if (skeleton.bones[boneIndex].id === id) {
  18247. return skeleton.bones[boneIndex];
  18248. }
  18249. }
  18250. }
  18251. return null;
  18252. };
  18253. /**
  18254. * get a bone using its id
  18255. * @param {string} the bone's name
  18256. * @return {BABYLON.Bone|null} the bone or null if not found
  18257. */
  18258. Scene.prototype.getBoneByName = function (name) {
  18259. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18260. var skeleton = this.skeletons[skeletonIndex];
  18261. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18262. if (skeleton.bones[boneIndex].name === name) {
  18263. return skeleton.bones[boneIndex];
  18264. }
  18265. }
  18266. }
  18267. return null;
  18268. };
  18269. /**
  18270. * get a light node using its name
  18271. * @param {string} the light's name
  18272. * @return {BABYLON.Light|null} the light or null if none found.
  18273. */
  18274. Scene.prototype.getLightByName = function (name) {
  18275. for (var index = 0; index < this.lights.length; index++) {
  18276. if (this.lights[index].name === name) {
  18277. return this.lights[index];
  18278. }
  18279. }
  18280. return null;
  18281. };
  18282. /**
  18283. * get a light node using its ID
  18284. * @param {string} the light's id
  18285. * @return {BABYLON.Light|null} the light or null if none found.
  18286. */
  18287. Scene.prototype.getLightByID = function (id) {
  18288. for (var index = 0; index < this.lights.length; index++) {
  18289. if (this.lights[index].id === id) {
  18290. return this.lights[index];
  18291. }
  18292. }
  18293. return null;
  18294. };
  18295. /**
  18296. * get a light node using its scene-generated unique ID
  18297. * @param {number} the light's unique id
  18298. * @return {BABYLON.Light|null} the light or null if none found.
  18299. */
  18300. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18301. for (var index = 0; index < this.lights.length; index++) {
  18302. if (this.lights[index].uniqueId === uniqueId) {
  18303. return this.lights[index];
  18304. }
  18305. }
  18306. return null;
  18307. };
  18308. /**
  18309. * get a particle system by id
  18310. * @param id {number} the particle system id
  18311. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18312. */
  18313. Scene.prototype.getParticleSystemByID = function (id) {
  18314. for (var index = 0; index < this.particleSystems.length; index++) {
  18315. if (this.particleSystems[index].id === id) {
  18316. return this.particleSystems[index];
  18317. }
  18318. }
  18319. return null;
  18320. };
  18321. /**
  18322. * get a geometry using its ID
  18323. * @param {string} the geometry's id
  18324. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18325. */
  18326. Scene.prototype.getGeometryByID = function (id) {
  18327. for (var index = 0; index < this._geometries.length; index++) {
  18328. if (this._geometries[index].id === id) {
  18329. return this._geometries[index];
  18330. }
  18331. }
  18332. return null;
  18333. };
  18334. /**
  18335. * add a new geometry to this scene.
  18336. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18337. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18338. * @return {boolean} was the geometry added or not
  18339. */
  18340. Scene.prototype.pushGeometry = function (geometry, force) {
  18341. if (!force && this.getGeometryByID(geometry.id)) {
  18342. return false;
  18343. }
  18344. this._geometries.push(geometry);
  18345. //notify the collision coordinator
  18346. if (this.collisionCoordinator) {
  18347. this.collisionCoordinator.onGeometryAdded(geometry);
  18348. }
  18349. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18350. return true;
  18351. };
  18352. /**
  18353. * Removes an existing geometry
  18354. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18355. * @return {boolean} was the geometry removed or not
  18356. */
  18357. Scene.prototype.removeGeometry = function (geometry) {
  18358. var index = this._geometries.indexOf(geometry);
  18359. if (index > -1) {
  18360. this._geometries.splice(index, 1);
  18361. //notify the collision coordinator
  18362. if (this.collisionCoordinator) {
  18363. this.collisionCoordinator.onGeometryDeleted(geometry);
  18364. }
  18365. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18366. return true;
  18367. }
  18368. return false;
  18369. };
  18370. Scene.prototype.getGeometries = function () {
  18371. return this._geometries;
  18372. };
  18373. /**
  18374. * Get the first added mesh found of a given ID
  18375. * @param {string} id - the id to search for
  18376. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18377. */
  18378. Scene.prototype.getMeshByID = function (id) {
  18379. for (var index = 0; index < this.meshes.length; index++) {
  18380. if (this.meshes[index].id === id) {
  18381. return this.meshes[index];
  18382. }
  18383. }
  18384. return null;
  18385. };
  18386. Scene.prototype.getMeshesByID = function (id) {
  18387. return this.meshes.filter(function (m) {
  18388. return m.id === id;
  18389. });
  18390. };
  18391. /**
  18392. * Get a mesh with its auto-generated unique id
  18393. * @param {number} uniqueId - the unique id to search for
  18394. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18395. */
  18396. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18397. for (var index = 0; index < this.meshes.length; index++) {
  18398. if (this.meshes[index].uniqueId === uniqueId) {
  18399. return this.meshes[index];
  18400. }
  18401. }
  18402. return null;
  18403. };
  18404. /**
  18405. * Get a the last added mesh found of a given ID
  18406. * @param {string} id - the id to search for
  18407. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18408. */
  18409. Scene.prototype.getLastMeshByID = function (id) {
  18410. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18411. if (this.meshes[index].id === id) {
  18412. return this.meshes[index];
  18413. }
  18414. }
  18415. return null;
  18416. };
  18417. /**
  18418. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18419. * @param {string} id - the id to search for
  18420. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18421. */
  18422. Scene.prototype.getLastEntryByID = function (id) {
  18423. var index;
  18424. for (index = this.meshes.length - 1; index >= 0; index--) {
  18425. if (this.meshes[index].id === id) {
  18426. return this.meshes[index];
  18427. }
  18428. }
  18429. for (index = this.cameras.length - 1; index >= 0; index--) {
  18430. if (this.cameras[index].id === id) {
  18431. return this.cameras[index];
  18432. }
  18433. }
  18434. for (index = this.lights.length - 1; index >= 0; index--) {
  18435. if (this.lights[index].id === id) {
  18436. return this.lights[index];
  18437. }
  18438. }
  18439. return null;
  18440. };
  18441. Scene.prototype.getNodeByID = function (id) {
  18442. var mesh = this.getMeshByID(id);
  18443. if (mesh) {
  18444. return mesh;
  18445. }
  18446. var light = this.getLightByID(id);
  18447. if (light) {
  18448. return light;
  18449. }
  18450. var camera = this.getCameraByID(id);
  18451. if (camera) {
  18452. return camera;
  18453. }
  18454. var bone = this.getBoneByID(id);
  18455. return bone;
  18456. };
  18457. Scene.prototype.getNodeByName = function (name) {
  18458. var mesh = this.getMeshByName(name);
  18459. if (mesh) {
  18460. return mesh;
  18461. }
  18462. var light = this.getLightByName(name);
  18463. if (light) {
  18464. return light;
  18465. }
  18466. var camera = this.getCameraByName(name);
  18467. if (camera) {
  18468. return camera;
  18469. }
  18470. var bone = this.getBoneByName(name);
  18471. return bone;
  18472. };
  18473. Scene.prototype.getMeshByName = function (name) {
  18474. for (var index = 0; index < this.meshes.length; index++) {
  18475. if (this.meshes[index].name === name) {
  18476. return this.meshes[index];
  18477. }
  18478. }
  18479. return null;
  18480. };
  18481. Scene.prototype.getSoundByName = function (name) {
  18482. var index;
  18483. if (BABYLON.AudioEngine) {
  18484. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18485. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18486. return this.mainSoundTrack.soundCollection[index];
  18487. }
  18488. }
  18489. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18490. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18491. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18492. return this.soundTracks[sdIndex].soundCollection[index];
  18493. }
  18494. }
  18495. }
  18496. }
  18497. return null;
  18498. };
  18499. Scene.prototype.getLastSkeletonByID = function (id) {
  18500. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18501. if (this.skeletons[index].id === id) {
  18502. return this.skeletons[index];
  18503. }
  18504. }
  18505. return null;
  18506. };
  18507. Scene.prototype.getSkeletonById = function (id) {
  18508. for (var index = 0; index < this.skeletons.length; index++) {
  18509. if (this.skeletons[index].id === id) {
  18510. return this.skeletons[index];
  18511. }
  18512. }
  18513. return null;
  18514. };
  18515. Scene.prototype.getSkeletonByName = function (name) {
  18516. for (var index = 0; index < this.skeletons.length; index++) {
  18517. if (this.skeletons[index].name === name) {
  18518. return this.skeletons[index];
  18519. }
  18520. }
  18521. return null;
  18522. };
  18523. Scene.prototype.getMorphTargetManagerById = function (id) {
  18524. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18525. if (this.morphTargetManagers[index].uniqueId === id) {
  18526. return this.morphTargetManagers[index];
  18527. }
  18528. }
  18529. return null;
  18530. };
  18531. Scene.prototype.isActiveMesh = function (mesh) {
  18532. return (this._activeMeshes.indexOf(mesh) !== -1);
  18533. };
  18534. /**
  18535. * Return a the first highlight layer of the scene with a given name.
  18536. * @param name The name of the highlight layer to look for.
  18537. * @return The highlight layer if found otherwise null.
  18538. */
  18539. Scene.prototype.getHighlightLayerByName = function (name) {
  18540. for (var index = 0; index < this.highlightLayers.length; index++) {
  18541. if (this.highlightLayers[index].name === name) {
  18542. return this.highlightLayers[index];
  18543. }
  18544. }
  18545. return null;
  18546. };
  18547. Object.defineProperty(Scene.prototype, "uid", {
  18548. /**
  18549. * Return a unique id as a string which can serve as an identifier for the scene
  18550. */
  18551. get: function () {
  18552. if (!this._uid) {
  18553. this._uid = BABYLON.Tools.RandomId();
  18554. }
  18555. return this._uid;
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. /**
  18561. * Add an externaly attached data from its key.
  18562. * This method call will fail and return false, if such key already exists.
  18563. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18564. * @param key the unique key that identifies the data
  18565. * @param data the data object to associate to the key for this Engine instance
  18566. * @return true if no such key were already present and the data was added successfully, false otherwise
  18567. */
  18568. Scene.prototype.addExternalData = function (key, data) {
  18569. if (!this._externalData) {
  18570. this._externalData = new BABYLON.StringDictionary();
  18571. }
  18572. return this._externalData.add(key, data);
  18573. };
  18574. /**
  18575. * Get an externaly attached data from its key
  18576. * @param key the unique key that identifies the data
  18577. * @return the associated data, if present (can be null), or undefined if not present
  18578. */
  18579. Scene.prototype.getExternalData = function (key) {
  18580. if (!this._externalData) {
  18581. return null;
  18582. }
  18583. return this._externalData.get(key);
  18584. };
  18585. /**
  18586. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18587. * @param key the unique key that identifies the data
  18588. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18589. * @return the associated data, can be null if the factory returned null.
  18590. */
  18591. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18592. if (!this._externalData) {
  18593. this._externalData = new BABYLON.StringDictionary();
  18594. }
  18595. return this._externalData.getOrAddWithFactory(key, factory);
  18596. };
  18597. /**
  18598. * Remove an externaly attached data from the Engine instance
  18599. * @param key the unique key that identifies the data
  18600. * @return true if the data was successfully removed, false if it doesn't exist
  18601. */
  18602. Scene.prototype.removeExternalData = function (key) {
  18603. return this._externalData.remove(key);
  18604. };
  18605. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18606. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18607. var material = subMesh.getMaterial();
  18608. if (mesh.showSubMeshesBoundingBox) {
  18609. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18610. }
  18611. if (material) {
  18612. // Render targets
  18613. if (material.getRenderTargetTextures) {
  18614. if (this._processedMaterials.indexOf(material) === -1) {
  18615. this._processedMaterials.push(material);
  18616. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18617. }
  18618. }
  18619. // Dispatch
  18620. this._activeIndices.addCount(subMesh.indexCount, false);
  18621. this._renderingManager.dispatch(subMesh);
  18622. }
  18623. }
  18624. };
  18625. Scene.prototype._isInIntermediateRendering = function () {
  18626. return this._intermediateRendering;
  18627. };
  18628. /**
  18629. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18630. */
  18631. Scene.prototype.freezeActiveMeshes = function () {
  18632. this._evaluateActiveMeshes();
  18633. this._activeMeshesFrozen = true;
  18634. return this;
  18635. };
  18636. /**
  18637. * Use this function to restart evaluating active meshes on every frame
  18638. */
  18639. Scene.prototype.unfreezeActiveMeshes = function () {
  18640. this._activeMeshesFrozen = false;
  18641. return this;
  18642. };
  18643. Scene.prototype._evaluateActiveMeshes = function () {
  18644. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18645. return;
  18646. }
  18647. this.activeCamera._activeMeshes.reset();
  18648. this._activeMeshes.reset();
  18649. this._renderingManager.reset();
  18650. this._processedMaterials.reset();
  18651. this._activeParticleSystems.reset();
  18652. this._activeSkeletons.reset();
  18653. this._softwareSkinnedMeshes.reset();
  18654. if (this._boundingBoxRenderer) {
  18655. this._boundingBoxRenderer.reset();
  18656. }
  18657. // Meshes
  18658. var meshes;
  18659. var len;
  18660. if (this._selectionOctree) {
  18661. var selection = this._selectionOctree.select(this._frustumPlanes);
  18662. meshes = selection.data;
  18663. len = selection.length;
  18664. }
  18665. else {
  18666. len = this.meshes.length;
  18667. meshes = this.meshes;
  18668. }
  18669. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18670. var mesh = meshes[meshIndex];
  18671. if (mesh.isBlocked) {
  18672. continue;
  18673. }
  18674. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18675. if (!mesh.isReady() || !mesh.isEnabled()) {
  18676. continue;
  18677. }
  18678. mesh.computeWorldMatrix();
  18679. // Intersections
  18680. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18681. this._meshesForIntersections.pushNoDuplicate(mesh);
  18682. }
  18683. // Switch to current LOD
  18684. var meshLOD = mesh.getLOD(this.activeCamera);
  18685. if (!meshLOD) {
  18686. continue;
  18687. }
  18688. mesh._preActivate();
  18689. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18690. this._activeMeshes.push(mesh);
  18691. this.activeCamera._activeMeshes.push(mesh);
  18692. mesh._activate(this._renderId);
  18693. if (meshLOD !== mesh) {
  18694. meshLOD._activate(this._renderId);
  18695. }
  18696. this._activeMesh(mesh, meshLOD);
  18697. }
  18698. }
  18699. // Particle systems
  18700. this._particlesDuration.beginMonitoring();
  18701. var beforeParticlesDate = BABYLON.Tools.Now;
  18702. if (this.particlesEnabled) {
  18703. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18704. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18705. var particleSystem = this.particleSystems[particleIndex];
  18706. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18707. continue;
  18708. }
  18709. var emitter = particleSystem.emitter;
  18710. if (!emitter.position || emitter.isEnabled()) {
  18711. this._activeParticleSystems.push(particleSystem);
  18712. particleSystem.animate();
  18713. this._renderingManager.dispatchParticles(particleSystem);
  18714. }
  18715. }
  18716. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18717. }
  18718. this._particlesDuration.endMonitoring(false);
  18719. };
  18720. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18721. if (mesh.skeleton && this.skeletonsEnabled) {
  18722. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18723. mesh.skeleton.prepare();
  18724. }
  18725. if (!mesh.computeBonesUsingShaders) {
  18726. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18727. }
  18728. }
  18729. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18730. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18731. }
  18732. if (mesh && mesh.subMeshes) {
  18733. // Submeshes Octrees
  18734. var len;
  18735. var subMeshes;
  18736. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18737. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18738. len = intersections.length;
  18739. subMeshes = intersections.data;
  18740. }
  18741. else {
  18742. subMeshes = mesh.subMeshes;
  18743. len = subMeshes.length;
  18744. }
  18745. for (var subIndex = 0; subIndex < len; subIndex++) {
  18746. var subMesh = subMeshes[subIndex];
  18747. this._evaluateSubMesh(subMesh, mesh);
  18748. }
  18749. }
  18750. };
  18751. Scene.prototype.updateTransformMatrix = function (force) {
  18752. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18753. };
  18754. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18755. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18756. };
  18757. Scene.prototype._renderForCamera = function (camera) {
  18758. if (camera && camera._skipRendering) {
  18759. return;
  18760. }
  18761. var engine = this._engine;
  18762. var startTime = BABYLON.Tools.Now;
  18763. this.activeCamera = camera;
  18764. if (!this.activeCamera)
  18765. throw new Error("Active camera not set");
  18766. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18767. // Viewport
  18768. engine.setViewport(this.activeCamera.viewport);
  18769. // Camera
  18770. this.resetCachedMaterial();
  18771. this._renderId++;
  18772. this.activeCamera.update();
  18773. this.updateTransformMatrix();
  18774. if (camera._alternateCamera) {
  18775. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18776. this._alternateRendering = true;
  18777. }
  18778. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18779. // Meshes
  18780. this._evaluateActiveMeshesDuration.beginMonitoring();
  18781. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18782. this._evaluateActiveMeshes();
  18783. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18784. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18785. // Software skinning
  18786. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18787. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18788. mesh.applySkeleton(mesh.skeleton);
  18789. }
  18790. // Render targets
  18791. this._renderTargetsDuration.beginMonitoring();
  18792. var needsRestoreFrameBuffer = false;
  18793. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18794. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18795. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18796. }
  18797. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18798. this._intermediateRendering = true;
  18799. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18800. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18801. var renderTarget = this._renderTargets.data[renderIndex];
  18802. if (renderTarget._shouldRender()) {
  18803. this._renderId++;
  18804. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18805. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18806. }
  18807. }
  18808. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18809. this._intermediateRendering = false;
  18810. this._renderId++;
  18811. needsRestoreFrameBuffer = true; // Restore back buffer
  18812. }
  18813. // Render HighlightLayer Texture
  18814. var stencilState = this._engine.getStencilBuffer();
  18815. var renderhighlights = false;
  18816. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18817. this._intermediateRendering = true;
  18818. for (var i = 0; i < this.highlightLayers.length; i++) {
  18819. var highlightLayer = this.highlightLayers[i];
  18820. if (highlightLayer.shouldRender() &&
  18821. (!highlightLayer.camera ||
  18822. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18823. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18824. renderhighlights = true;
  18825. var renderTarget = highlightLayer._mainTexture;
  18826. if (renderTarget._shouldRender()) {
  18827. this._renderId++;
  18828. renderTarget.render(false, false);
  18829. needsRestoreFrameBuffer = true;
  18830. }
  18831. }
  18832. }
  18833. this._intermediateRendering = false;
  18834. this._renderId++;
  18835. }
  18836. if (needsRestoreFrameBuffer) {
  18837. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18838. }
  18839. this._renderTargetsDuration.endMonitoring(false);
  18840. // Prepare Frame
  18841. this.postProcessManager._prepareFrame();
  18842. this._renderDuration.beginMonitoring();
  18843. // Backgrounds
  18844. var layerIndex;
  18845. var layer;
  18846. if (this.layers.length) {
  18847. engine.setDepthBuffer(false);
  18848. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18849. layer = this.layers[layerIndex];
  18850. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18851. layer.render();
  18852. }
  18853. }
  18854. engine.setDepthBuffer(true);
  18855. }
  18856. // Render
  18857. BABYLON.Tools.StartPerformanceCounter("Main render");
  18858. // Activate HighlightLayer stencil
  18859. if (renderhighlights) {
  18860. this._engine.setStencilBuffer(true);
  18861. }
  18862. this._renderingManager.render(null, null, true, true);
  18863. // Restore HighlightLayer stencil
  18864. if (renderhighlights) {
  18865. this._engine.setStencilBuffer(stencilState);
  18866. }
  18867. BABYLON.Tools.EndPerformanceCounter("Main render");
  18868. // Bounding boxes
  18869. if (this._boundingBoxRenderer) {
  18870. this._boundingBoxRenderer.render();
  18871. }
  18872. // Lens flares
  18873. if (this.lensFlaresEnabled) {
  18874. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18875. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18876. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18877. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18878. lensFlareSystem.render();
  18879. }
  18880. }
  18881. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18882. }
  18883. // Foregrounds
  18884. if (this.layers.length) {
  18885. engine.setDepthBuffer(false);
  18886. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18887. layer = this.layers[layerIndex];
  18888. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18889. layer.render();
  18890. }
  18891. }
  18892. engine.setDepthBuffer(true);
  18893. }
  18894. // Highlight Layer
  18895. if (renderhighlights) {
  18896. engine.setDepthBuffer(false);
  18897. for (var i = 0; i < this.highlightLayers.length; i++) {
  18898. if (this.highlightLayers[i].shouldRender()) {
  18899. this.highlightLayers[i].render();
  18900. }
  18901. }
  18902. engine.setDepthBuffer(true);
  18903. }
  18904. this._renderDuration.endMonitoring(false);
  18905. // Finalize frame
  18906. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18907. // Reset some special arrays
  18908. this._renderTargets.reset();
  18909. this._alternateRendering = false;
  18910. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18911. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18912. };
  18913. Scene.prototype._processSubCameras = function (camera) {
  18914. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18915. this._renderForCamera(camera);
  18916. return;
  18917. }
  18918. // Update camera
  18919. this.activeCamera.update();
  18920. // rig cameras
  18921. for (var index = 0; index < camera._rigCameras.length; index++) {
  18922. this._renderForCamera(camera._rigCameras[index]);
  18923. }
  18924. this.activeCamera = camera;
  18925. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18926. };
  18927. Scene.prototype._checkIntersections = function () {
  18928. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18929. var sourceMesh = this._meshesForIntersections.data[index];
  18930. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18931. var action = sourceMesh.actionManager.actions[actionIndex];
  18932. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18933. var parameters = action.getTriggerParameter();
  18934. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18935. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18936. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18937. if (areIntersecting && currentIntersectionInProgress === -1) {
  18938. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18939. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18940. sourceMesh._intersectionsInProgress.push(otherMesh);
  18941. }
  18942. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18943. sourceMesh._intersectionsInProgress.push(otherMesh);
  18944. }
  18945. }
  18946. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18947. //They intersected, and now they don't.
  18948. //is this trigger an exit trigger? execute an event.
  18949. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18950. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18951. }
  18952. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18953. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18954. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18955. }
  18956. }
  18957. }
  18958. }
  18959. }
  18960. };
  18961. Scene.prototype.render = function () {
  18962. if (this.isDisposed) {
  18963. return;
  18964. }
  18965. this._interFrameDuration.endMonitoring();
  18966. this._lastFrameDuration.beginMonitoring();
  18967. this._particlesDuration.fetchNewFrame();
  18968. this._spritesDuration.fetchNewFrame();
  18969. this._activeParticles.fetchNewFrame();
  18970. this._renderDuration.fetchNewFrame();
  18971. this._renderTargetsDuration.fetchNewFrame();
  18972. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18973. this._totalVertices.fetchNewFrame();
  18974. this._activeIndices.fetchNewFrame();
  18975. this._activeBones.fetchNewFrame();
  18976. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18977. this._meshesForIntersections.reset();
  18978. this.resetCachedMaterial();
  18979. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18980. // Actions
  18981. if (this.actionManager) {
  18982. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18983. }
  18984. //Simplification Queue
  18985. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18986. this.simplificationQueue.executeNext();
  18987. }
  18988. if (this._engine.isDeterministicLockStep()) {
  18989. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18990. var defaultTimeStep = (60.0 / 1000.0);
  18991. if (this._physicsEngine) {
  18992. defaultTimeStep = this._physicsEngine.getTimeStep();
  18993. }
  18994. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18995. this._timeAccumulator += deltaTime;
  18996. // compute the amount of fixed steps we should have taken since the last step
  18997. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18998. internalSteps = Math.min(internalSteps, maxSubSteps);
  18999. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19000. this.onBeforeStepObservable.notifyObservers(this);
  19001. // Animations
  19002. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19003. this._animate();
  19004. // Physics
  19005. if (this._physicsEngine) {
  19006. BABYLON.Tools.StartPerformanceCounter("Physics");
  19007. this._physicsEngine._step(defaultTimeStep);
  19008. BABYLON.Tools.EndPerformanceCounter("Physics");
  19009. }
  19010. this._timeAccumulator -= defaultTimeStep;
  19011. this.onAfterStepObservable.notifyObservers(this);
  19012. this._currentStepId++;
  19013. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19014. this._evaluateActiveMeshes();
  19015. }
  19016. }
  19017. }
  19018. else {
  19019. // Animations
  19020. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19021. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19022. this._animate();
  19023. // Physics
  19024. if (this._physicsEngine) {
  19025. BABYLON.Tools.StartPerformanceCounter("Physics");
  19026. this._physicsEngine._step(deltaTime / 1000.0);
  19027. BABYLON.Tools.EndPerformanceCounter("Physics");
  19028. }
  19029. }
  19030. // Before render
  19031. this.onBeforeRenderObservable.notifyObservers(this);
  19032. // Customs render targets
  19033. this._renderTargetsDuration.beginMonitoring();
  19034. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19035. var engine = this.getEngine();
  19036. var currentActiveCamera = this.activeCamera;
  19037. if (this.renderTargetsEnabled) {
  19038. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19039. this._intermediateRendering = true;
  19040. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19041. var renderTarget = this.customRenderTargets[customIndex];
  19042. if (renderTarget._shouldRender()) {
  19043. this._renderId++;
  19044. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19045. if (!this.activeCamera)
  19046. throw new Error("Active camera not set");
  19047. // Viewport
  19048. engine.setViewport(this.activeCamera.viewport);
  19049. // Camera
  19050. this.updateTransformMatrix();
  19051. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19052. }
  19053. }
  19054. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19055. this._intermediateRendering = false;
  19056. this._renderId++;
  19057. }
  19058. // Restore back buffer
  19059. if (this.customRenderTargets.length > 0) {
  19060. engine.restoreDefaultFramebuffer();
  19061. }
  19062. this._renderTargetsDuration.endMonitoring();
  19063. this.activeCamera = currentActiveCamera;
  19064. // Procedural textures
  19065. if (this.proceduralTexturesEnabled) {
  19066. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19067. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19068. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19069. if (proceduralTexture._shouldRender()) {
  19070. proceduralTexture.render();
  19071. }
  19072. }
  19073. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19074. }
  19075. // Clear
  19076. if (this.autoClearDepthAndStencil || this.autoClear) {
  19077. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19078. }
  19079. // Shadows
  19080. if (this.shadowsEnabled) {
  19081. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19082. var light = this.lights[lightIndex];
  19083. var shadowGenerator = light.getShadowGenerator();
  19084. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19085. var shadowMap = shadowGenerator.getShadowMap();
  19086. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19087. this._renderTargets.push(shadowMap);
  19088. }
  19089. }
  19090. }
  19091. }
  19092. // Depth renderer
  19093. if (this._depthRenderer) {
  19094. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19095. }
  19096. // Geometry renderer
  19097. if (this._geometryBufferRenderer) {
  19098. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19099. }
  19100. // RenderPipeline
  19101. if (this._postProcessRenderPipelineManager) {
  19102. this._postProcessRenderPipelineManager.update();
  19103. }
  19104. // Multi-cameras?
  19105. if (this.activeCameras.length > 0) {
  19106. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19107. if (cameraIndex > 0) {
  19108. this._engine.clear(null, false, true, true);
  19109. }
  19110. this._processSubCameras(this.activeCameras[cameraIndex]);
  19111. }
  19112. }
  19113. else {
  19114. if (!this.activeCamera) {
  19115. throw new Error("No camera defined");
  19116. }
  19117. this._processSubCameras(this.activeCamera);
  19118. }
  19119. // Intersection checks
  19120. this._checkIntersections();
  19121. // Update the audio listener attached to the camera
  19122. if (BABYLON.AudioEngine) {
  19123. this._updateAudioParameters();
  19124. }
  19125. // After render
  19126. if (this.afterRender) {
  19127. this.afterRender();
  19128. }
  19129. this.onAfterRenderObservable.notifyObservers(this);
  19130. // Cleaning
  19131. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19132. this._toBeDisposed.data[index].dispose();
  19133. this._toBeDisposed[index] = null;
  19134. }
  19135. this._toBeDisposed.reset();
  19136. if (this.dumpNextRenderTargets) {
  19137. this.dumpNextRenderTargets = false;
  19138. }
  19139. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19140. this._interFrameDuration.beginMonitoring();
  19141. this._lastFrameDuration.endMonitoring();
  19142. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19143. this._totalLightsCounter.addCount(this.lights.length, true);
  19144. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19145. this._totalTexturesCounter.addCount(this.textures.length, true);
  19146. this._activeBones.addCount(0, true);
  19147. this._activeIndices.addCount(0, true);
  19148. this._activeParticles.addCount(0, true);
  19149. };
  19150. Scene.prototype._updateAudioParameters = function () {
  19151. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19152. return;
  19153. }
  19154. var listeningCamera;
  19155. var audioEngine = BABYLON.Engine.audioEngine;
  19156. if (this.activeCameras.length > 0) {
  19157. listeningCamera = this.activeCameras[0];
  19158. }
  19159. else {
  19160. listeningCamera = this.activeCamera;
  19161. }
  19162. if (listeningCamera && audioEngine.canUseWebAudio) {
  19163. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19164. // for VR cameras
  19165. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19166. listeningCamera = listeningCamera.rigCameras[0];
  19167. }
  19168. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19169. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19170. cameraDirection.normalize();
  19171. // To avoid some errors on GearVR
  19172. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19173. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19174. }
  19175. var i;
  19176. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19177. var sound = this.mainSoundTrack.soundCollection[i];
  19178. if (sound.useCustomAttenuation) {
  19179. sound.updateDistanceFromListener();
  19180. }
  19181. }
  19182. for (i = 0; i < this.soundTracks.length; i++) {
  19183. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19184. sound = this.soundTracks[i].soundCollection[j];
  19185. if (sound.useCustomAttenuation) {
  19186. sound.updateDistanceFromListener();
  19187. }
  19188. }
  19189. }
  19190. }
  19191. };
  19192. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19193. // Audio
  19194. get: function () {
  19195. return this._audioEnabled;
  19196. },
  19197. set: function (value) {
  19198. this._audioEnabled = value;
  19199. if (BABYLON.AudioEngine) {
  19200. if (this._audioEnabled) {
  19201. this._enableAudio();
  19202. }
  19203. else {
  19204. this._disableAudio();
  19205. }
  19206. }
  19207. },
  19208. enumerable: true,
  19209. configurable: true
  19210. });
  19211. Scene.prototype._disableAudio = function () {
  19212. var i;
  19213. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19214. this.mainSoundTrack.soundCollection[i].pause();
  19215. }
  19216. for (i = 0; i < this.soundTracks.length; i++) {
  19217. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19218. this.soundTracks[i].soundCollection[j].pause();
  19219. }
  19220. }
  19221. };
  19222. Scene.prototype._enableAudio = function () {
  19223. var i;
  19224. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19225. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19226. this.mainSoundTrack.soundCollection[i].play();
  19227. }
  19228. }
  19229. for (i = 0; i < this.soundTracks.length; i++) {
  19230. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19231. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19232. this.soundTracks[i].soundCollection[j].play();
  19233. }
  19234. }
  19235. }
  19236. };
  19237. Object.defineProperty(Scene.prototype, "headphone", {
  19238. get: function () {
  19239. return this._headphone;
  19240. },
  19241. set: function (value) {
  19242. this._headphone = value;
  19243. if (BABYLON.AudioEngine) {
  19244. if (this._headphone) {
  19245. this._switchAudioModeForHeadphones();
  19246. }
  19247. else {
  19248. this._switchAudioModeForNormalSpeakers();
  19249. }
  19250. }
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Scene.prototype._switchAudioModeForHeadphones = function () {
  19256. this.mainSoundTrack.switchPanningModelToHRTF();
  19257. for (var i = 0; i < this.soundTracks.length; i++) {
  19258. this.soundTracks[i].switchPanningModelToHRTF();
  19259. }
  19260. };
  19261. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19262. this.mainSoundTrack.switchPanningModelToEqualPower();
  19263. for (var i = 0; i < this.soundTracks.length; i++) {
  19264. this.soundTracks[i].switchPanningModelToEqualPower();
  19265. }
  19266. };
  19267. Scene.prototype.enableDepthRenderer = function () {
  19268. if (this._depthRenderer) {
  19269. return this._depthRenderer;
  19270. }
  19271. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19272. return this._depthRenderer;
  19273. };
  19274. Scene.prototype.disableDepthRenderer = function () {
  19275. if (!this._depthRenderer) {
  19276. return;
  19277. }
  19278. this._depthRenderer.dispose();
  19279. this._depthRenderer = null;
  19280. };
  19281. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19282. if (ratio === void 0) { ratio = 1; }
  19283. if (this._geometryBufferRenderer) {
  19284. return this._geometryBufferRenderer;
  19285. }
  19286. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19287. if (!this._geometryBufferRenderer.isSupported) {
  19288. this._geometryBufferRenderer = null;
  19289. }
  19290. return this._geometryBufferRenderer;
  19291. };
  19292. Scene.prototype.disableGeometryBufferRenderer = function () {
  19293. if (!this._geometryBufferRenderer) {
  19294. return;
  19295. }
  19296. this._geometryBufferRenderer.dispose();
  19297. this._geometryBufferRenderer = null;
  19298. };
  19299. Scene.prototype.freezeMaterials = function () {
  19300. for (var i = 0; i < this.materials.length; i++) {
  19301. this.materials[i].freeze();
  19302. }
  19303. };
  19304. Scene.prototype.unfreezeMaterials = function () {
  19305. for (var i = 0; i < this.materials.length; i++) {
  19306. this.materials[i].unfreeze();
  19307. }
  19308. };
  19309. Scene.prototype.dispose = function () {
  19310. this.beforeRender = null;
  19311. this.afterRender = null;
  19312. this.skeletons = [];
  19313. this.morphTargetManagers = [];
  19314. this.importedMeshesFiles = new Array();
  19315. this.resetCachedMaterial();
  19316. if (this._depthRenderer) {
  19317. this._depthRenderer.dispose();
  19318. }
  19319. if (this._gamepadManager) {
  19320. this._gamepadManager.dispose();
  19321. this._gamepadManager = null;
  19322. }
  19323. // Smart arrays
  19324. if (this.activeCamera) {
  19325. this.activeCamera._activeMeshes.dispose();
  19326. this.activeCamera = null;
  19327. }
  19328. this._activeMeshes.dispose();
  19329. this._renderingManager.dispose();
  19330. this._processedMaterials.dispose();
  19331. this._activeParticleSystems.dispose();
  19332. this._activeSkeletons.dispose();
  19333. this._softwareSkinnedMeshes.dispose();
  19334. this._renderTargets.dispose();
  19335. if (this._boundingBoxRenderer) {
  19336. this._boundingBoxRenderer.dispose();
  19337. }
  19338. this._meshesForIntersections.dispose();
  19339. this._toBeDisposed.dispose();
  19340. // Debug layer
  19341. if (this._debugLayer) {
  19342. this._debugLayer.hide();
  19343. }
  19344. // Events
  19345. this.onDisposeObservable.notifyObservers(this);
  19346. this.onDisposeObservable.clear();
  19347. this.onBeforeRenderObservable.clear();
  19348. this.onAfterRenderObservable.clear();
  19349. this.detachControl();
  19350. // Release sounds & sounds tracks
  19351. if (BABYLON.AudioEngine) {
  19352. this.disposeSounds();
  19353. }
  19354. // VR Helper
  19355. if (this.VRHelper) {
  19356. this.VRHelper.dispose();
  19357. }
  19358. // Detach cameras
  19359. var canvas = this._engine.getRenderingCanvas();
  19360. var index;
  19361. for (index = 0; index < this.cameras.length; index++) {
  19362. this.cameras[index].detachControl(canvas);
  19363. }
  19364. // Release lights
  19365. while (this.lights.length) {
  19366. this.lights[0].dispose();
  19367. }
  19368. // Release meshes
  19369. while (this.meshes.length) {
  19370. this.meshes[0].dispose(true);
  19371. }
  19372. // Release cameras
  19373. while (this.cameras.length) {
  19374. this.cameras[0].dispose();
  19375. }
  19376. // Release materials
  19377. if (this.defaultMaterial) {
  19378. this.defaultMaterial.dispose();
  19379. }
  19380. while (this.multiMaterials.length) {
  19381. this.multiMaterials[0].dispose();
  19382. }
  19383. while (this.materials.length) {
  19384. this.materials[0].dispose();
  19385. }
  19386. // Release particles
  19387. while (this.particleSystems.length) {
  19388. this.particleSystems[0].dispose();
  19389. }
  19390. // Release sprites
  19391. while (this.spriteManagers.length) {
  19392. this.spriteManagers[0].dispose();
  19393. }
  19394. // Release postProcesses
  19395. while (this.postProcesses.length) {
  19396. this.postProcesses[0].dispose();
  19397. }
  19398. // Release layers
  19399. while (this.layers.length) {
  19400. this.layers[0].dispose();
  19401. }
  19402. while (this.highlightLayers.length) {
  19403. this.highlightLayers[0].dispose();
  19404. }
  19405. // Release textures
  19406. while (this.textures.length) {
  19407. this.textures[0].dispose();
  19408. }
  19409. // Release UBO
  19410. this._sceneUbo.dispose();
  19411. if (this._alternateSceneUbo) {
  19412. this._alternateSceneUbo.dispose();
  19413. }
  19414. // Post-processes
  19415. this.postProcessManager.dispose();
  19416. if (this._postProcessRenderPipelineManager) {
  19417. this._postProcessRenderPipelineManager.dispose();
  19418. }
  19419. // Physics
  19420. if (this._physicsEngine) {
  19421. this.disablePhysicsEngine();
  19422. }
  19423. // Remove from engine
  19424. index = this._engine.scenes.indexOf(this);
  19425. if (index > -1) {
  19426. this._engine.scenes.splice(index, 1);
  19427. }
  19428. this._engine.wipeCaches();
  19429. this._engine = null;
  19430. this.defaultMaterial = null;
  19431. this.multiMaterials = null;
  19432. this.materials = null;
  19433. };
  19434. Object.defineProperty(Scene.prototype, "isDisposed", {
  19435. get: function () {
  19436. return !this._engine;
  19437. },
  19438. enumerable: true,
  19439. configurable: true
  19440. });
  19441. // Release sounds & sounds tracks
  19442. Scene.prototype.disposeSounds = function () {
  19443. this.mainSoundTrack.dispose();
  19444. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19445. this.soundTracks[scIndex].dispose();
  19446. }
  19447. };
  19448. // Octrees
  19449. Scene.prototype.getWorldExtends = function () {
  19450. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19451. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19452. for (var index = 0; index < this.meshes.length; index++) {
  19453. var mesh = this.meshes[index];
  19454. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19455. continue;
  19456. }
  19457. mesh.computeWorldMatrix(true);
  19458. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19459. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19460. BABYLON.Tools.CheckExtends(minBox, min, max);
  19461. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19462. }
  19463. return {
  19464. min: min,
  19465. max: max
  19466. };
  19467. };
  19468. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19469. if (maxCapacity === void 0) { maxCapacity = 64; }
  19470. if (maxDepth === void 0) { maxDepth = 2; }
  19471. if (!this._selectionOctree) {
  19472. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19473. }
  19474. var worldExtends = this.getWorldExtends();
  19475. // Update octree
  19476. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19477. return this._selectionOctree;
  19478. };
  19479. // Picking
  19480. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19481. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19482. var engine = this._engine;
  19483. if (!camera) {
  19484. if (!this.activeCamera)
  19485. throw new Error("Active camera not set");
  19486. camera = this.activeCamera;
  19487. }
  19488. var cameraViewport = camera.viewport;
  19489. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19490. // Moving coordinates to local viewport world
  19491. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19492. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19493. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19494. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19495. };
  19496. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19497. if (!BABYLON.PickingInfo) {
  19498. return null;
  19499. }
  19500. var engine = this._engine;
  19501. if (!camera) {
  19502. if (!this.activeCamera)
  19503. throw new Error("Active camera not set");
  19504. camera = this.activeCamera;
  19505. }
  19506. var cameraViewport = camera.viewport;
  19507. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19508. var identity = BABYLON.Matrix.Identity();
  19509. // Moving coordinates to local viewport world
  19510. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19511. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19512. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19513. };
  19514. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19515. if (!BABYLON.PickingInfo) {
  19516. return null;
  19517. }
  19518. var pickingInfo = null;
  19519. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19520. var mesh = this.meshes[meshIndex];
  19521. if (predicate) {
  19522. if (!predicate(mesh)) {
  19523. continue;
  19524. }
  19525. }
  19526. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19527. continue;
  19528. }
  19529. var world = mesh.getWorldMatrix();
  19530. var ray = rayFunction(world);
  19531. var result = mesh.intersects(ray, fastCheck);
  19532. if (!result || !result.hit)
  19533. continue;
  19534. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19535. continue;
  19536. pickingInfo = result;
  19537. if (fastCheck) {
  19538. break;
  19539. }
  19540. }
  19541. return pickingInfo || new BABYLON.PickingInfo();
  19542. };
  19543. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19544. if (!BABYLON.PickingInfo) {
  19545. return null;
  19546. }
  19547. var pickingInfos = new Array();
  19548. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19549. var mesh = this.meshes[meshIndex];
  19550. if (predicate) {
  19551. if (!predicate(mesh)) {
  19552. continue;
  19553. }
  19554. }
  19555. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19556. continue;
  19557. }
  19558. var world = mesh.getWorldMatrix();
  19559. var ray = rayFunction(world);
  19560. var result = mesh.intersects(ray, false);
  19561. if (!result || !result.hit)
  19562. continue;
  19563. pickingInfos.push(result);
  19564. }
  19565. return pickingInfos;
  19566. };
  19567. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19568. if (!BABYLON.PickingInfo) {
  19569. return null;
  19570. }
  19571. var pickingInfo = null;
  19572. camera = camera || this.activeCamera;
  19573. if (this.spriteManagers.length > 0) {
  19574. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19575. var spriteManager = this.spriteManagers[spriteIndex];
  19576. if (!spriteManager.isPickable) {
  19577. continue;
  19578. }
  19579. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19580. if (!result || !result.hit)
  19581. continue;
  19582. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19583. continue;
  19584. pickingInfo = result;
  19585. if (fastCheck) {
  19586. break;
  19587. }
  19588. }
  19589. }
  19590. return pickingInfo || new BABYLON.PickingInfo();
  19591. };
  19592. /** Launch a ray to try to pick a mesh in the scene
  19593. * @param x position on screen
  19594. * @param y position on screen
  19595. * @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
  19596. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19597. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19598. */
  19599. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19600. var _this = this;
  19601. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19602. };
  19603. /** Launch a ray to try to pick a sprite in the scene
  19604. * @param x position on screen
  19605. * @param y position on screen
  19606. * @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
  19607. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19608. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19609. */
  19610. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19611. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19612. };
  19613. /** Use the given ray to pick a mesh in the scene
  19614. * @param ray The ray to use to pick meshes
  19615. * @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
  19616. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19617. */
  19618. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19619. var _this = this;
  19620. return this._internalPick(function (world) {
  19621. if (!_this._pickWithRayInverseMatrix) {
  19622. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19623. }
  19624. world.invertToRef(_this._pickWithRayInverseMatrix);
  19625. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19626. }, predicate, fastCheck);
  19627. };
  19628. /**
  19629. * Launch a ray to try to pick a mesh in the scene
  19630. * @param x X position on screen
  19631. * @param y Y position on screen
  19632. * @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
  19633. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19634. */
  19635. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19636. var _this = this;
  19637. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19638. };
  19639. /**
  19640. * Launch a ray to try to pick a mesh in the scene
  19641. * @param ray Ray to use
  19642. * @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
  19643. */
  19644. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19645. var _this = this;
  19646. return this._internalMultiPick(function (world) {
  19647. if (!_this._pickWithRayInverseMatrix) {
  19648. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19649. }
  19650. world.invertToRef(_this._pickWithRayInverseMatrix);
  19651. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19652. }, predicate);
  19653. };
  19654. Scene.prototype.setPointerOverMesh = function (mesh) {
  19655. if (this._pointerOverMesh === mesh) {
  19656. return;
  19657. }
  19658. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19659. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19660. }
  19661. this._pointerOverMesh = mesh;
  19662. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19663. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19664. }
  19665. };
  19666. Scene.prototype.getPointerOverMesh = function () {
  19667. return this._pointerOverMesh;
  19668. };
  19669. Scene.prototype.setPointerOverSprite = function (sprite) {
  19670. if (this._pointerOverSprite === sprite) {
  19671. return;
  19672. }
  19673. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19674. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19675. }
  19676. this._pointerOverSprite = sprite;
  19677. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19678. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19679. }
  19680. };
  19681. Scene.prototype.getPointerOverSprite = function () {
  19682. return this._pointerOverSprite;
  19683. };
  19684. // Physics
  19685. Scene.prototype.getPhysicsEngine = function () {
  19686. return this._physicsEngine;
  19687. };
  19688. /**
  19689. * Enables physics to the current scene
  19690. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19691. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19692. * @return {boolean} was the physics engine initialized
  19693. */
  19694. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19695. if (this._physicsEngine) {
  19696. return true;
  19697. }
  19698. try {
  19699. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19700. return true;
  19701. }
  19702. catch (e) {
  19703. BABYLON.Tools.Error(e.message);
  19704. return false;
  19705. }
  19706. };
  19707. Scene.prototype.disablePhysicsEngine = function () {
  19708. if (!this._physicsEngine) {
  19709. return;
  19710. }
  19711. this._physicsEngine.dispose();
  19712. this._physicsEngine = undefined;
  19713. };
  19714. Scene.prototype.isPhysicsEnabled = function () {
  19715. return this._physicsEngine !== undefined;
  19716. };
  19717. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19718. var mesh = compound.parts[0].mesh;
  19719. mesh.physicsImpostor.dispose();
  19720. mesh.physicsImpostor = null;
  19721. };
  19722. // Misc.
  19723. Scene.prototype._rebuildGeometries = function () {
  19724. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19725. var geometry = _a[_i];
  19726. geometry._rebuild();
  19727. }
  19728. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19729. var mesh = _c[_b];
  19730. mesh._rebuild();
  19731. }
  19732. if (this.postProcessManager) {
  19733. this.postProcessManager._rebuild();
  19734. }
  19735. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19736. var layer = _e[_d];
  19737. layer._rebuild();
  19738. }
  19739. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19740. var highlightLayer = _g[_f];
  19741. highlightLayer._rebuild();
  19742. }
  19743. if (this._boundingBoxRenderer) {
  19744. this._boundingBoxRenderer._rebuild();
  19745. }
  19746. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19747. var system = _j[_h];
  19748. system.rebuild();
  19749. }
  19750. if (this._postProcessRenderPipelineManager) {
  19751. this._postProcessRenderPipelineManager._rebuild();
  19752. }
  19753. };
  19754. Scene.prototype._rebuildTextures = function () {
  19755. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19756. var texture = _a[_i];
  19757. texture._rebuild();
  19758. }
  19759. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19760. };
  19761. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19762. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19763. if (replace === void 0) { replace = false; }
  19764. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19765. // Dispose existing camera or light in replace mode.
  19766. if (replace) {
  19767. if (this.activeCamera) {
  19768. this.activeCamera.dispose();
  19769. this.activeCamera = null;
  19770. }
  19771. if (this.lights) {
  19772. for (var i = 0; i < this.lights.length; i++) {
  19773. this.lights[i].dispose();
  19774. }
  19775. }
  19776. }
  19777. // Light
  19778. if (this.lights.length === 0) {
  19779. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19780. }
  19781. // Camera
  19782. if (!this.activeCamera) {
  19783. var worldExtends = this.getWorldExtends();
  19784. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19785. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19786. var camera;
  19787. var radius = worldSize.length() * 1.5;
  19788. if (createArcRotateCamera) {
  19789. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19790. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19791. arcRotateCamera.wheelPrecision = 100 / radius;
  19792. camera = arcRotateCamera;
  19793. }
  19794. else {
  19795. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19796. freeCamera.setTarget(worldCenter);
  19797. camera = freeCamera;
  19798. }
  19799. camera.minZ = radius * 0.01;
  19800. camera.maxZ = radius * 100;
  19801. camera.speed = radius * 0.2;
  19802. this.activeCamera = camera;
  19803. if (attachCameraControls) {
  19804. camera.attachControl(this.getEngine().getRenderingCanvas());
  19805. }
  19806. }
  19807. };
  19808. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19809. if (pbr === void 0) { pbr = false; }
  19810. if (scale === void 0) { scale = 1000; }
  19811. if (blur === void 0) { blur = 0; }
  19812. if (environmentTexture) {
  19813. this.environmentTexture = environmentTexture;
  19814. }
  19815. if (!this.environmentTexture) {
  19816. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19817. return;
  19818. }
  19819. // Skybox
  19820. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19821. if (pbr) {
  19822. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19823. hdrSkyboxMaterial.backFaceCulling = false;
  19824. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19825. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19826. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19827. hdrSkyboxMaterial.disableLighting = true;
  19828. hdrSkyboxMaterial.twoSidedLighting = true;
  19829. hdrSkybox.infiniteDistance = true;
  19830. hdrSkybox.material = hdrSkyboxMaterial;
  19831. }
  19832. else {
  19833. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19834. skyboxMaterial.backFaceCulling = false;
  19835. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19836. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19837. skyboxMaterial.disableLighting = true;
  19838. hdrSkybox.infiniteDistance = true;
  19839. hdrSkybox.material = skyboxMaterial;
  19840. }
  19841. return hdrSkybox;
  19842. };
  19843. Scene.prototype.createDefaultVRExperience = function () {
  19844. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19845. };
  19846. // Tags
  19847. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19848. if (tagsQuery === undefined) {
  19849. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19850. return list;
  19851. }
  19852. var listByTags = [];
  19853. forEach = forEach || (function (item) { return; });
  19854. for (var i in list) {
  19855. var item = list[i];
  19856. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19857. listByTags.push(item);
  19858. forEach(item);
  19859. }
  19860. }
  19861. return listByTags;
  19862. };
  19863. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19864. return this._getByTags(this.meshes, tagsQuery, forEach);
  19865. };
  19866. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19867. return this._getByTags(this.cameras, tagsQuery, forEach);
  19868. };
  19869. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19870. return this._getByTags(this.lights, tagsQuery, forEach);
  19871. };
  19872. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19873. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19874. };
  19875. /**
  19876. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19877. * This allowed control for front to back rendering or reversly depending of the special needs.
  19878. *
  19879. * @param renderingGroupId The rendering group id corresponding to its index
  19880. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19881. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19882. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19883. */
  19884. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19885. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19886. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19887. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19888. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19889. };
  19890. /**
  19891. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19892. *
  19893. * @param renderingGroupId The rendering group id corresponding to its index
  19894. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19895. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19896. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19897. */
  19898. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19899. if (depth === void 0) { depth = true; }
  19900. if (stencil === void 0) { stencil = true; }
  19901. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19902. };
  19903. /**
  19904. * Will flag all materials as dirty to trigger new shader compilation
  19905. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19906. */
  19907. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19908. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19909. var material = _a[_i];
  19910. if (predicate && !predicate(material)) {
  19911. continue;
  19912. }
  19913. material.markAsDirty(flag);
  19914. }
  19915. };
  19916. // Statics
  19917. Scene._FOGMODE_NONE = 0;
  19918. Scene._FOGMODE_EXP = 1;
  19919. Scene._FOGMODE_EXP2 = 2;
  19920. Scene._FOGMODE_LINEAR = 3;
  19921. Scene.MinDeltaTime = 1.0;
  19922. Scene.MaxDeltaTime = 1000.0;
  19923. /** The distance in pixel that you have to move to prevent some events */
  19924. Scene.DragMovementThreshold = 10; // in pixels
  19925. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19926. Scene.LongPressDelay = 500; // in milliseconds
  19927. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19928. Scene.DoubleClickDelay = 300; // in milliseconds
  19929. /** If you need to check double click without raising a single click at first click, enable this flag */
  19930. Scene.ExclusiveDoubleClickMode = false;
  19931. return Scene;
  19932. }());
  19933. BABYLON.Scene = Scene;
  19934. })(BABYLON || (BABYLON = {}));
  19935. //# sourceMappingURL=babylon.scene.js.map
  19936. var BABYLON;
  19937. (function (BABYLON) {
  19938. var Buffer = (function () {
  19939. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19940. if (engine instanceof BABYLON.Mesh) {
  19941. this._engine = engine.getScene().getEngine();
  19942. }
  19943. else {
  19944. this._engine = engine;
  19945. }
  19946. this._updatable = updatable;
  19947. this._data = data;
  19948. this._strideSize = stride;
  19949. if (!postponeInternalCreation) {
  19950. this.create();
  19951. }
  19952. this._instanced = instanced;
  19953. this._instanceDivisor = instanced ? 1 : 0;
  19954. }
  19955. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19956. // a lot of these parameters are ignored as they are overriden by the buffer
  19957. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19958. };
  19959. // Properties
  19960. Buffer.prototype.isUpdatable = function () {
  19961. return this._updatable;
  19962. };
  19963. Buffer.prototype.getData = function () {
  19964. return this._data;
  19965. };
  19966. Buffer.prototype.getBuffer = function () {
  19967. return this._buffer;
  19968. };
  19969. Buffer.prototype.getStrideSize = function () {
  19970. return this._strideSize;
  19971. };
  19972. Buffer.prototype.getIsInstanced = function () {
  19973. return this._instanced;
  19974. };
  19975. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19976. get: function () {
  19977. return this._instanceDivisor;
  19978. },
  19979. set: function (value) {
  19980. this._instanceDivisor = value;
  19981. if (value == 0) {
  19982. this._instanced = false;
  19983. }
  19984. else {
  19985. this._instanced = true;
  19986. }
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. // Methods
  19992. Buffer.prototype.create = function (data) {
  19993. if (!data && this._buffer) {
  19994. return; // nothing to do
  19995. }
  19996. data = data || this._data;
  19997. if (!this._buffer) {
  19998. if (this._updatable) {
  19999. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20000. this._data = data;
  20001. }
  20002. else {
  20003. this._buffer = this._engine.createVertexBuffer(data);
  20004. }
  20005. }
  20006. else if (this._updatable) {
  20007. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20008. this._data = data;
  20009. }
  20010. };
  20011. Buffer.prototype._rebuild = function () {
  20012. this._buffer = null;
  20013. this.create(this._data);
  20014. };
  20015. Buffer.prototype.update = function (data) {
  20016. this.create(data);
  20017. };
  20018. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20019. if (!this._buffer) {
  20020. return;
  20021. }
  20022. if (this._updatable) {
  20023. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20024. this._data = null;
  20025. }
  20026. };
  20027. Buffer.prototype.dispose = function () {
  20028. if (!this._buffer) {
  20029. return;
  20030. }
  20031. if (this._engine._releaseBuffer(this._buffer)) {
  20032. this._buffer = null;
  20033. }
  20034. };
  20035. return Buffer;
  20036. }());
  20037. BABYLON.Buffer = Buffer;
  20038. })(BABYLON || (BABYLON = {}));
  20039. //# sourceMappingURL=babylon.buffer.js.map
  20040. var BABYLON;
  20041. (function (BABYLON) {
  20042. var VertexBuffer = (function () {
  20043. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20044. if (!stride) {
  20045. // Deduce stride from kind
  20046. switch (kind) {
  20047. case VertexBuffer.PositionKind:
  20048. stride = 3;
  20049. break;
  20050. case VertexBuffer.NormalKind:
  20051. stride = 3;
  20052. break;
  20053. case VertexBuffer.UVKind:
  20054. case VertexBuffer.UV2Kind:
  20055. case VertexBuffer.UV3Kind:
  20056. case VertexBuffer.UV4Kind:
  20057. case VertexBuffer.UV5Kind:
  20058. case VertexBuffer.UV6Kind:
  20059. stride = 2;
  20060. break;
  20061. case VertexBuffer.TangentKind:
  20062. case VertexBuffer.ColorKind:
  20063. stride = 4;
  20064. break;
  20065. case VertexBuffer.MatricesIndicesKind:
  20066. case VertexBuffer.MatricesIndicesExtraKind:
  20067. stride = 4;
  20068. break;
  20069. case VertexBuffer.MatricesWeightsKind:
  20070. case VertexBuffer.MatricesWeightsExtraKind:
  20071. stride = 4;
  20072. break;
  20073. }
  20074. }
  20075. if (data instanceof BABYLON.Buffer) {
  20076. if (!stride) {
  20077. stride = data.getStrideSize();
  20078. }
  20079. this._buffer = data;
  20080. this._ownsBuffer = false;
  20081. }
  20082. else {
  20083. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20084. this._ownsBuffer = true;
  20085. }
  20086. this._stride = stride;
  20087. this._offset = offset ? offset : 0;
  20088. this._size = size ? size : stride;
  20089. this._kind = kind;
  20090. }
  20091. VertexBuffer.prototype._rebuild = function () {
  20092. if (!this._buffer) {
  20093. return;
  20094. }
  20095. this._buffer._rebuild();
  20096. };
  20097. /**
  20098. * Returns the kind of the VertexBuffer (string).
  20099. */
  20100. VertexBuffer.prototype.getKind = function () {
  20101. return this._kind;
  20102. };
  20103. // Properties
  20104. /**
  20105. * Boolean : is the VertexBuffer updatable ?
  20106. */
  20107. VertexBuffer.prototype.isUpdatable = function () {
  20108. return this._buffer.isUpdatable();
  20109. };
  20110. /**
  20111. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20112. */
  20113. VertexBuffer.prototype.getData = function () {
  20114. return this._buffer.getData();
  20115. };
  20116. /**
  20117. * Returns the WebGLBuffer associated to the VertexBuffer.
  20118. */
  20119. VertexBuffer.prototype.getBuffer = function () {
  20120. return this._buffer.getBuffer();
  20121. };
  20122. /**
  20123. * Returns the stride of the VertexBuffer (integer).
  20124. */
  20125. VertexBuffer.prototype.getStrideSize = function () {
  20126. return this._stride;
  20127. };
  20128. /**
  20129. * Returns the offset (integer).
  20130. */
  20131. VertexBuffer.prototype.getOffset = function () {
  20132. return this._offset;
  20133. };
  20134. /**
  20135. * Returns the VertexBuffer total size (integer).
  20136. */
  20137. VertexBuffer.prototype.getSize = function () {
  20138. return this._size;
  20139. };
  20140. /**
  20141. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20142. */
  20143. VertexBuffer.prototype.getIsInstanced = function () {
  20144. return this._buffer.getIsInstanced();
  20145. };
  20146. /**
  20147. * Returns the instancing divisor, zero for non-instanced (integer).
  20148. */
  20149. VertexBuffer.prototype.getInstanceDivisor = function () {
  20150. return this._buffer.instanceDivisor;
  20151. };
  20152. // Methods
  20153. /**
  20154. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20155. * Returns the created WebGLBuffer.
  20156. */
  20157. VertexBuffer.prototype.create = function (data) {
  20158. return this._buffer.create(data);
  20159. };
  20160. /**
  20161. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20162. * Returns the updated WebGLBuffer.
  20163. */
  20164. VertexBuffer.prototype.update = function (data) {
  20165. return this._buffer.update(data);
  20166. };
  20167. /**
  20168. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20169. * Returns the directly updated WebGLBuffer.
  20170. */
  20171. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20172. return this._buffer.updateDirectly(data, offset);
  20173. };
  20174. /**
  20175. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20176. */
  20177. VertexBuffer.prototype.dispose = function () {
  20178. if (this._ownsBuffer) {
  20179. this._buffer.dispose();
  20180. }
  20181. };
  20182. Object.defineProperty(VertexBuffer, "PositionKind", {
  20183. get: function () {
  20184. return VertexBuffer._PositionKind;
  20185. },
  20186. enumerable: true,
  20187. configurable: true
  20188. });
  20189. Object.defineProperty(VertexBuffer, "NormalKind", {
  20190. get: function () {
  20191. return VertexBuffer._NormalKind;
  20192. },
  20193. enumerable: true,
  20194. configurable: true
  20195. });
  20196. Object.defineProperty(VertexBuffer, "TangentKind", {
  20197. get: function () {
  20198. return VertexBuffer._TangentKind;
  20199. },
  20200. enumerable: true,
  20201. configurable: true
  20202. });
  20203. Object.defineProperty(VertexBuffer, "UVKind", {
  20204. get: function () {
  20205. return VertexBuffer._UVKind;
  20206. },
  20207. enumerable: true,
  20208. configurable: true
  20209. });
  20210. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20211. get: function () {
  20212. return VertexBuffer._UV2Kind;
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20218. get: function () {
  20219. return VertexBuffer._UV3Kind;
  20220. },
  20221. enumerable: true,
  20222. configurable: true
  20223. });
  20224. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20225. get: function () {
  20226. return VertexBuffer._UV4Kind;
  20227. },
  20228. enumerable: true,
  20229. configurable: true
  20230. });
  20231. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20232. get: function () {
  20233. return VertexBuffer._UV5Kind;
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20239. get: function () {
  20240. return VertexBuffer._UV6Kind;
  20241. },
  20242. enumerable: true,
  20243. configurable: true
  20244. });
  20245. Object.defineProperty(VertexBuffer, "ColorKind", {
  20246. get: function () {
  20247. return VertexBuffer._ColorKind;
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20253. get: function () {
  20254. return VertexBuffer._MatricesIndicesKind;
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20260. get: function () {
  20261. return VertexBuffer._MatricesWeightsKind;
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20267. get: function () {
  20268. return VertexBuffer._MatricesIndicesExtraKind;
  20269. },
  20270. enumerable: true,
  20271. configurable: true
  20272. });
  20273. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20274. get: function () {
  20275. return VertexBuffer._MatricesWeightsExtraKind;
  20276. },
  20277. enumerable: true,
  20278. configurable: true
  20279. });
  20280. // Enums
  20281. VertexBuffer._PositionKind = "position";
  20282. VertexBuffer._NormalKind = "normal";
  20283. VertexBuffer._TangentKind = "tangent";
  20284. VertexBuffer._UVKind = "uv";
  20285. VertexBuffer._UV2Kind = "uv2";
  20286. VertexBuffer._UV3Kind = "uv3";
  20287. VertexBuffer._UV4Kind = "uv4";
  20288. VertexBuffer._UV5Kind = "uv5";
  20289. VertexBuffer._UV6Kind = "uv6";
  20290. VertexBuffer._ColorKind = "color";
  20291. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20292. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20293. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20294. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20295. return VertexBuffer;
  20296. }());
  20297. BABYLON.VertexBuffer = VertexBuffer;
  20298. })(BABYLON || (BABYLON = {}));
  20299. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20300. var BABYLON;
  20301. (function (BABYLON) {
  20302. var InternalTexture = (function () {
  20303. function InternalTexture(engine, dataSource) {
  20304. this.onLoadedObservable = new BABYLON.Observable();
  20305. // Private
  20306. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20307. this._references = 1;
  20308. this._engine = engine;
  20309. this._dataSource = dataSource;
  20310. this._webGLTexture = engine._createTexture();
  20311. }
  20312. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20313. get: function () {
  20314. return this._dataSource;
  20315. },
  20316. enumerable: true,
  20317. configurable: true
  20318. });
  20319. InternalTexture.prototype.incrementReferences = function () {
  20320. this._references++;
  20321. };
  20322. InternalTexture.prototype.updateSize = function (width, height) {
  20323. this.width = width;
  20324. this.height = height;
  20325. this._size = width * height;
  20326. this.baseWidth = width;
  20327. this.baseHeight = height;
  20328. };
  20329. InternalTexture.prototype._rebuild = function () {
  20330. var _this = this;
  20331. var proxy;
  20332. this.isReady = false;
  20333. this._cachedCoordinatesMode = null;
  20334. this._cachedWrapU = null;
  20335. this._cachedWrapV = null;
  20336. this._cachedAnisotropicFilteringLevel = null;
  20337. switch (this._dataSource) {
  20338. case InternalTexture.DATASOURCE_TEMP:
  20339. return;
  20340. case InternalTexture.DATASOURCE_URL:
  20341. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20342. _this.isReady = true;
  20343. }, null, this._buffer, null, this.format);
  20344. proxy._swapAndDie(this);
  20345. return;
  20346. case InternalTexture.DATASOURCE_RAW:
  20347. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20348. proxy._swapAndDie(this);
  20349. this.isReady = true;
  20350. return;
  20351. case InternalTexture.DATASOURCE_DYNAMIC:
  20352. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20353. proxy._swapAndDie(this);
  20354. // The engine will make sure to update content so no need to flag it as isReady = true
  20355. return;
  20356. case InternalTexture.DATASOURCE_RENDERTARGET:
  20357. var options = new BABYLON.RenderTargetCreationOptions();
  20358. options.generateDepthBuffer = this._generateDepthBuffer;
  20359. options.generateMipMaps = this.generateMipMaps;
  20360. options.generateStencilBuffer = this._generateStencilBuffer;
  20361. options.samplingMode = this.samplingMode;
  20362. options.type = this.type;
  20363. if (this.isCube) {
  20364. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20365. }
  20366. else {
  20367. var size = {
  20368. width: this.width,
  20369. height: this.height
  20370. };
  20371. proxy = this._engine.createRenderTargetTexture(size, options);
  20372. }
  20373. proxy._swapAndDie(this);
  20374. this.isReady = true;
  20375. return;
  20376. case InternalTexture.DATASOURCE_CUBE:
  20377. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20378. _this.isReady = true;
  20379. }, null, this.format, this._extension);
  20380. proxy._swapAndDie(this);
  20381. return;
  20382. case InternalTexture.DATASOURCE_CUBERAW:
  20383. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20384. proxy._swapAndDie(this);
  20385. this.isReady = true;
  20386. return;
  20387. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20388. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20389. proxy._swapAndDie(_this);
  20390. _this.isReady = true;
  20391. }, null, this.format, this._extension);
  20392. return;
  20393. }
  20394. };
  20395. InternalTexture.prototype._swapAndDie = function (target) {
  20396. target._webGLTexture = this._webGLTexture;
  20397. if (this._framebuffer) {
  20398. target._framebuffer = this._framebuffer;
  20399. }
  20400. if (this._depthStencilBuffer) {
  20401. target._depthStencilBuffer = this._depthStencilBuffer;
  20402. }
  20403. if (this._lodTextureHigh) {
  20404. if (target._lodTextureHigh) {
  20405. target._lodTextureHigh.dispose();
  20406. }
  20407. target._lodTextureHigh = this._lodTextureHigh;
  20408. }
  20409. if (this._lodTextureMid) {
  20410. if (target._lodTextureMid) {
  20411. target._lodTextureMid.dispose();
  20412. }
  20413. target._lodTextureMid = this._lodTextureMid;
  20414. }
  20415. if (this._lodTextureLow) {
  20416. if (target._lodTextureLow) {
  20417. target._lodTextureLow.dispose();
  20418. }
  20419. target._lodTextureLow = this._lodTextureLow;
  20420. }
  20421. var cache = this._engine.getLoadedTexturesCache();
  20422. var index = cache.indexOf(this);
  20423. if (index !== -1) {
  20424. cache.splice(index, 1);
  20425. }
  20426. };
  20427. InternalTexture.prototype.dispose = function () {
  20428. if (!this._webGLTexture) {
  20429. return;
  20430. }
  20431. this._references--;
  20432. if (this._references === 0) {
  20433. this._engine._releaseTexture(this);
  20434. this._webGLTexture = null;
  20435. }
  20436. };
  20437. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20438. InternalTexture.DATASOURCE_URL = 1;
  20439. InternalTexture.DATASOURCE_TEMP = 2;
  20440. InternalTexture.DATASOURCE_RAW = 3;
  20441. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20442. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20443. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20444. InternalTexture.DATASOURCE_CUBE = 7;
  20445. InternalTexture.DATASOURCE_CUBERAW = 8;
  20446. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20447. return InternalTexture;
  20448. }());
  20449. BABYLON.InternalTexture = InternalTexture;
  20450. })(BABYLON || (BABYLON = {}));
  20451. //# sourceMappingURL=babylon.internalTexture.js.map
  20452. var BABYLON;
  20453. (function (BABYLON) {
  20454. var BaseTexture = (function () {
  20455. function BaseTexture(scene) {
  20456. this._hasAlpha = false;
  20457. this.getAlphaFromRGB = false;
  20458. this.level = 1;
  20459. this.coordinatesIndex = 0;
  20460. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20461. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20462. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20463. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20464. this.isCube = false;
  20465. this.gammaSpace = true;
  20466. this.invertZ = false;
  20467. this.lodLevelInAlpha = false;
  20468. this.lodGenerationOffset = 0.0;
  20469. this.lodGenerationScale = 0.8;
  20470. this.isRenderTarget = false;
  20471. this.animations = new Array();
  20472. /**
  20473. * An event triggered when the texture is disposed.
  20474. * @type {BABYLON.Observable}
  20475. */
  20476. this.onDisposeObservable = new BABYLON.Observable();
  20477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20478. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20479. this._scene.textures.push(this);
  20480. this._uid = null;
  20481. }
  20482. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20483. get: function () {
  20484. return this._hasAlpha;
  20485. },
  20486. set: function (value) {
  20487. if (this._hasAlpha === value) {
  20488. return;
  20489. }
  20490. this._hasAlpha = value;
  20491. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20492. },
  20493. enumerable: true,
  20494. configurable: true
  20495. });
  20496. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20497. get: function () {
  20498. return this._coordinatesMode;
  20499. },
  20500. set: function (value) {
  20501. if (this._coordinatesMode === value) {
  20502. return;
  20503. }
  20504. this._coordinatesMode = value;
  20505. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20506. },
  20507. enumerable: true,
  20508. configurable: true
  20509. });
  20510. Object.defineProperty(BaseTexture.prototype, "uid", {
  20511. get: function () {
  20512. if (!this._uid) {
  20513. this._uid = BABYLON.Tools.RandomId();
  20514. }
  20515. return this._uid;
  20516. },
  20517. enumerable: true,
  20518. configurable: true
  20519. });
  20520. BaseTexture.prototype.toString = function () {
  20521. return this.name;
  20522. };
  20523. BaseTexture.prototype.getClassName = function () {
  20524. return "BaseTexture";
  20525. };
  20526. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20527. set: function (callback) {
  20528. if (this._onDisposeObserver) {
  20529. this.onDisposeObservable.remove(this._onDisposeObserver);
  20530. }
  20531. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20532. },
  20533. enumerable: true,
  20534. configurable: true
  20535. });
  20536. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20537. get: function () {
  20538. return true;
  20539. },
  20540. enumerable: true,
  20541. configurable: true
  20542. });
  20543. BaseTexture.prototype.getScene = function () {
  20544. return this._scene;
  20545. };
  20546. BaseTexture.prototype.getTextureMatrix = function () {
  20547. return null;
  20548. };
  20549. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20550. return null;
  20551. };
  20552. BaseTexture.prototype.getInternalTexture = function () {
  20553. return this._texture;
  20554. };
  20555. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20556. return !this.isBlocking || this.isReady();
  20557. };
  20558. BaseTexture.prototype.isReady = function () {
  20559. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20560. this.delayLoad();
  20561. return false;
  20562. }
  20563. if (this._texture) {
  20564. return this._texture.isReady;
  20565. }
  20566. return false;
  20567. };
  20568. BaseTexture.prototype.getSize = function () {
  20569. if (this._texture.width) {
  20570. return new BABYLON.Size(this._texture.width, this._texture.height);
  20571. }
  20572. if (this._texture._size) {
  20573. return new BABYLON.Size(this._texture._size, this._texture._size);
  20574. }
  20575. return BABYLON.Size.Zero();
  20576. };
  20577. BaseTexture.prototype.getBaseSize = function () {
  20578. if (!this.isReady() || !this._texture)
  20579. return BABYLON.Size.Zero();
  20580. if (this._texture._size) {
  20581. return new BABYLON.Size(this._texture._size, this._texture._size);
  20582. }
  20583. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20584. };
  20585. BaseTexture.prototype.scale = function (ratio) {
  20586. };
  20587. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20588. get: function () {
  20589. return false;
  20590. },
  20591. enumerable: true,
  20592. configurable: true
  20593. });
  20594. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20595. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20596. for (var index = 0; index < texturesCache.length; index++) {
  20597. var texturesCacheEntry = texturesCache[index];
  20598. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20599. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20600. texturesCacheEntry.incrementReferences();
  20601. return texturesCacheEntry;
  20602. }
  20603. }
  20604. }
  20605. return null;
  20606. };
  20607. BaseTexture.prototype._rebuild = function () {
  20608. };
  20609. BaseTexture.prototype.delayLoad = function () {
  20610. };
  20611. BaseTexture.prototype.clone = function () {
  20612. return null;
  20613. };
  20614. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20615. get: function () {
  20616. if (!this._texture) {
  20617. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20618. }
  20619. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20620. },
  20621. enumerable: true,
  20622. configurable: true
  20623. });
  20624. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20625. get: function () {
  20626. if (!this._texture) {
  20627. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20628. }
  20629. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. BaseTexture.prototype.readPixels = function (faceIndex) {
  20635. if (faceIndex === void 0) { faceIndex = 0; }
  20636. if (!this._texture) {
  20637. return null;
  20638. }
  20639. var size = this.getSize();
  20640. var engine = this.getScene().getEngine();
  20641. if (this._texture.isCube) {
  20642. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20643. }
  20644. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20645. };
  20646. BaseTexture.prototype.releaseInternalTexture = function () {
  20647. if (this._texture) {
  20648. this._texture.dispose();
  20649. this._texture = null;
  20650. }
  20651. };
  20652. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20653. get: function () {
  20654. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20655. return null;
  20656. }
  20657. if (!this._texture._sphericalPolynomial) {
  20658. this._texture._sphericalPolynomial =
  20659. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20660. }
  20661. return this._texture._sphericalPolynomial;
  20662. },
  20663. set: function (value) {
  20664. if (this._texture) {
  20665. this._texture._sphericalPolynomial = value;
  20666. }
  20667. },
  20668. enumerable: true,
  20669. configurable: true
  20670. });
  20671. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20672. get: function () {
  20673. if (this._texture) {
  20674. return this._texture._lodTextureHigh;
  20675. }
  20676. return null;
  20677. },
  20678. enumerable: true,
  20679. configurable: true
  20680. });
  20681. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20682. get: function () {
  20683. if (this._texture) {
  20684. return this._texture._lodTextureMid;
  20685. }
  20686. return null;
  20687. },
  20688. enumerable: true,
  20689. configurable: true
  20690. });
  20691. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20692. get: function () {
  20693. if (this._texture) {
  20694. return this._texture._lodTextureLow;
  20695. }
  20696. return null;
  20697. },
  20698. enumerable: true,
  20699. configurable: true
  20700. });
  20701. BaseTexture.prototype.dispose = function () {
  20702. // Animations
  20703. this.getScene().stopAnimation(this);
  20704. // Remove from scene
  20705. this._scene._removePendingData(this);
  20706. var index = this._scene.textures.indexOf(this);
  20707. if (index >= 0) {
  20708. this._scene.textures.splice(index, 1);
  20709. }
  20710. if (this._texture === undefined) {
  20711. return;
  20712. }
  20713. // Release
  20714. this.releaseInternalTexture();
  20715. // Callback
  20716. this.onDisposeObservable.notifyObservers(this);
  20717. this.onDisposeObservable.clear();
  20718. };
  20719. BaseTexture.prototype.serialize = function () {
  20720. if (!this.name) {
  20721. return null;
  20722. }
  20723. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20724. // Animations
  20725. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20726. return serializationObject;
  20727. };
  20728. BaseTexture.WhenAllReady = function (textures, callback) {
  20729. var numRemaining = textures.length;
  20730. if (numRemaining === 0) {
  20731. callback();
  20732. return;
  20733. }
  20734. var _loop_1 = function () {
  20735. texture = textures[i];
  20736. if (texture.isReady()) {
  20737. if (--numRemaining === 0) {
  20738. callback();
  20739. }
  20740. }
  20741. else {
  20742. onLoadObservable = texture.onLoadObservable;
  20743. var onLoadCallback_1 = function () {
  20744. onLoadObservable.removeCallback(onLoadCallback_1);
  20745. if (--numRemaining === 0) {
  20746. callback();
  20747. }
  20748. };
  20749. onLoadObservable.add(onLoadCallback_1);
  20750. }
  20751. };
  20752. var texture, onLoadObservable;
  20753. for (var i = 0; i < textures.length; i++) {
  20754. _loop_1();
  20755. }
  20756. };
  20757. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20758. __decorate([
  20759. BABYLON.serialize()
  20760. ], BaseTexture.prototype, "name", void 0);
  20761. __decorate([
  20762. BABYLON.serialize("hasAlpha")
  20763. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20764. __decorate([
  20765. BABYLON.serialize()
  20766. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20767. __decorate([
  20768. BABYLON.serialize()
  20769. ], BaseTexture.prototype, "level", void 0);
  20770. __decorate([
  20771. BABYLON.serialize()
  20772. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20773. __decorate([
  20774. BABYLON.serialize("coordinatesMode")
  20775. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20776. __decorate([
  20777. BABYLON.serialize()
  20778. ], BaseTexture.prototype, "wrapU", void 0);
  20779. __decorate([
  20780. BABYLON.serialize()
  20781. ], BaseTexture.prototype, "wrapV", void 0);
  20782. __decorate([
  20783. BABYLON.serialize()
  20784. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20785. __decorate([
  20786. BABYLON.serialize()
  20787. ], BaseTexture.prototype, "isCube", void 0);
  20788. __decorate([
  20789. BABYLON.serialize()
  20790. ], BaseTexture.prototype, "gammaSpace", void 0);
  20791. __decorate([
  20792. BABYLON.serialize()
  20793. ], BaseTexture.prototype, "invertZ", void 0);
  20794. __decorate([
  20795. BABYLON.serialize()
  20796. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20797. __decorate([
  20798. BABYLON.serialize()
  20799. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20800. __decorate([
  20801. BABYLON.serialize()
  20802. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20803. __decorate([
  20804. BABYLON.serialize()
  20805. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20806. return BaseTexture;
  20807. }());
  20808. BABYLON.BaseTexture = BaseTexture;
  20809. })(BABYLON || (BABYLON = {}));
  20810. //# sourceMappingURL=babylon.baseTexture.js.map
  20811. var BABYLON;
  20812. (function (BABYLON) {
  20813. var Texture = (function (_super) {
  20814. __extends(Texture, _super);
  20815. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20816. if (noMipmap === void 0) { noMipmap = false; }
  20817. if (invertY === void 0) { invertY = true; }
  20818. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20819. if (onLoad === void 0) { onLoad = null; }
  20820. if (onError === void 0) { onError = null; }
  20821. if (buffer === void 0) { buffer = null; }
  20822. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20823. var _this = _super.call(this, scene) || this;
  20824. _this.uOffset = 0;
  20825. _this.vOffset = 0;
  20826. _this.uScale = 1.0;
  20827. _this.vScale = 1.0;
  20828. _this.uAng = 0;
  20829. _this.vAng = 0;
  20830. _this.wAng = 0;
  20831. _this._isBlocking = true;
  20832. _this.name = url;
  20833. _this.url = url;
  20834. _this._noMipmap = noMipmap;
  20835. _this._invertY = invertY;
  20836. _this._samplingMode = samplingMode;
  20837. _this._buffer = buffer;
  20838. _this._deleteBuffer = deleteBuffer;
  20839. _this._format = format;
  20840. scene = _this.getScene();
  20841. var load = function () {
  20842. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20843. _this.onLoadObservable.notifyObservers(_this);
  20844. }
  20845. if (onLoad) {
  20846. onLoad();
  20847. }
  20848. if (!_this.isBlocking) {
  20849. scene.resetCachedMaterial();
  20850. }
  20851. };
  20852. if (!url) {
  20853. _this._delayedOnLoad = load;
  20854. _this._delayedOnError = onError;
  20855. return _this;
  20856. }
  20857. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20858. if (!_this._texture) {
  20859. if (!scene.useDelayedTextureLoading) {
  20860. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20861. if (deleteBuffer) {
  20862. delete _this._buffer;
  20863. }
  20864. }
  20865. else {
  20866. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20867. _this._delayedOnLoad = load;
  20868. _this._delayedOnError = onError;
  20869. }
  20870. }
  20871. else {
  20872. if (_this._texture.isReady) {
  20873. BABYLON.Tools.SetImmediate(function () { return load(); });
  20874. }
  20875. else {
  20876. _this._texture.onLoadedObservable.add(load);
  20877. }
  20878. }
  20879. return _this;
  20880. }
  20881. Object.defineProperty(Texture.prototype, "noMipmap", {
  20882. get: function () {
  20883. return this._noMipmap;
  20884. },
  20885. enumerable: true,
  20886. configurable: true
  20887. });
  20888. Object.defineProperty(Texture.prototype, "isBlocking", {
  20889. get: function () {
  20890. return this._isBlocking;
  20891. },
  20892. set: function (value) {
  20893. this._isBlocking = value;
  20894. },
  20895. enumerable: true,
  20896. configurable: true
  20897. });
  20898. Object.defineProperty(Texture.prototype, "samplingMode", {
  20899. get: function () {
  20900. return this._samplingMode;
  20901. },
  20902. enumerable: true,
  20903. configurable: true
  20904. });
  20905. Texture.prototype.updateURL = function (url) {
  20906. this.url = url;
  20907. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20908. this.delayLoad();
  20909. };
  20910. Texture.prototype.delayLoad = function () {
  20911. var _this = this;
  20912. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20913. return;
  20914. }
  20915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20916. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20917. if (!this._texture) {
  20918. 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);
  20919. if (this._deleteBuffer) {
  20920. delete this._buffer;
  20921. }
  20922. }
  20923. else {
  20924. if (this._texture.isReady) {
  20925. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20926. }
  20927. else {
  20928. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20929. }
  20930. }
  20931. };
  20932. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20933. if (!this._texture) {
  20934. return;
  20935. }
  20936. this._samplingMode = samplingMode;
  20937. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20938. };
  20939. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20940. x *= this.uScale;
  20941. y *= this.vScale;
  20942. x -= 0.5 * this.uScale;
  20943. y -= 0.5 * this.vScale;
  20944. z -= 0.5;
  20945. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20946. t.x += 0.5 * this.uScale + this.uOffset;
  20947. t.y += 0.5 * this.vScale + this.vOffset;
  20948. t.z += 0.5;
  20949. };
  20950. Texture.prototype.getTextureMatrix = function () {
  20951. var _this = this;
  20952. if (this.uOffset === this._cachedUOffset &&
  20953. this.vOffset === this._cachedVOffset &&
  20954. this.uScale === this._cachedUScale &&
  20955. this.vScale === this._cachedVScale &&
  20956. this.uAng === this._cachedUAng &&
  20957. this.vAng === this._cachedVAng &&
  20958. this.wAng === this._cachedWAng) {
  20959. return this._cachedTextureMatrix;
  20960. }
  20961. this._cachedUOffset = this.uOffset;
  20962. this._cachedVOffset = this.vOffset;
  20963. this._cachedUScale = this.uScale;
  20964. this._cachedVScale = this.vScale;
  20965. this._cachedUAng = this.uAng;
  20966. this._cachedVAng = this.vAng;
  20967. this._cachedWAng = this.wAng;
  20968. if (!this._cachedTextureMatrix) {
  20969. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20970. this._rowGenerationMatrix = new BABYLON.Matrix();
  20971. this._t0 = BABYLON.Vector3.Zero();
  20972. this._t1 = BABYLON.Vector3.Zero();
  20973. this._t2 = BABYLON.Vector3.Zero();
  20974. }
  20975. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20976. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20977. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20978. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20979. this._t1.subtractInPlace(this._t0);
  20980. this._t2.subtractInPlace(this._t0);
  20981. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20982. this._cachedTextureMatrix.m[0] = this._t1.x;
  20983. this._cachedTextureMatrix.m[1] = this._t1.y;
  20984. this._cachedTextureMatrix.m[2] = this._t1.z;
  20985. this._cachedTextureMatrix.m[4] = this._t2.x;
  20986. this._cachedTextureMatrix.m[5] = this._t2.y;
  20987. this._cachedTextureMatrix.m[6] = this._t2.z;
  20988. this._cachedTextureMatrix.m[8] = this._t0.x;
  20989. this._cachedTextureMatrix.m[9] = this._t0.y;
  20990. this._cachedTextureMatrix.m[10] = this._t0.z;
  20991. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20992. return mat.hasTexture(_this);
  20993. });
  20994. return this._cachedTextureMatrix;
  20995. };
  20996. Texture.prototype.getReflectionTextureMatrix = function () {
  20997. var _this = this;
  20998. var scene = this.getScene();
  20999. if (this.uOffset === this._cachedUOffset &&
  21000. this.vOffset === this._cachedVOffset &&
  21001. this.uScale === this._cachedUScale &&
  21002. this.vScale === this._cachedVScale &&
  21003. this.coordinatesMode === this._cachedCoordinatesMode) {
  21004. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21005. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21006. return this._cachedTextureMatrix;
  21007. }
  21008. }
  21009. else {
  21010. return this._cachedTextureMatrix;
  21011. }
  21012. }
  21013. if (!this._cachedTextureMatrix) {
  21014. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21015. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21016. }
  21017. this._cachedUOffset = this.uOffset;
  21018. this._cachedVOffset = this.vOffset;
  21019. this._cachedUScale = this.uScale;
  21020. this._cachedVScale = this.vScale;
  21021. this._cachedCoordinatesMode = this.coordinatesMode;
  21022. switch (this.coordinatesMode) {
  21023. case Texture.PLANAR_MODE:
  21024. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21025. this._cachedTextureMatrix[0] = this.uScale;
  21026. this._cachedTextureMatrix[5] = this.vScale;
  21027. this._cachedTextureMatrix[12] = this.uOffset;
  21028. this._cachedTextureMatrix[13] = this.vOffset;
  21029. break;
  21030. case Texture.PROJECTION_MODE:
  21031. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21032. this._projectionModeMatrix.m[0] = 0.5;
  21033. this._projectionModeMatrix.m[5] = -0.5;
  21034. this._projectionModeMatrix.m[10] = 0.0;
  21035. this._projectionModeMatrix.m[12] = 0.5;
  21036. this._projectionModeMatrix.m[13] = 0.5;
  21037. this._projectionModeMatrix.m[14] = 1.0;
  21038. this._projectionModeMatrix.m[15] = 1.0;
  21039. var projectionMatrix = scene.getProjectionMatrix();
  21040. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21041. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21042. break;
  21043. default:
  21044. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21045. break;
  21046. }
  21047. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21048. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21049. });
  21050. return this._cachedTextureMatrix;
  21051. };
  21052. Texture.prototype.clone = function () {
  21053. var _this = this;
  21054. return BABYLON.SerializationHelper.Clone(function () {
  21055. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21056. }, this);
  21057. };
  21058. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21059. get: function () {
  21060. if (!this._onLoadObservable) {
  21061. this._onLoadObservable = new BABYLON.Observable();
  21062. }
  21063. return this._onLoadObservable;
  21064. },
  21065. enumerable: true,
  21066. configurable: true
  21067. });
  21068. Texture.prototype.serialize = function () {
  21069. var serializationObject = _super.prototype.serialize.call(this);
  21070. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21071. serializationObject.base64String = this._buffer;
  21072. serializationObject.name = serializationObject.name.replace("data:", "");
  21073. }
  21074. return serializationObject;
  21075. };
  21076. Texture.prototype.getClassName = function () {
  21077. return "Texture";
  21078. };
  21079. Texture.prototype.dispose = function () {
  21080. _super.prototype.dispose.call(this);
  21081. if (this.onLoadObservable) {
  21082. this.onLoadObservable.clear();
  21083. this._onLoadObservable = null;
  21084. }
  21085. this._delayedOnLoad = null;
  21086. this._delayedOnError = null;
  21087. };
  21088. // Statics
  21089. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21090. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21091. if (onLoad === void 0) { onLoad = null; }
  21092. if (onError === void 0) { onError = null; }
  21093. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21094. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21095. };
  21096. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21097. if (parsedTexture.customType) {
  21098. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21099. // Update Sampling Mode
  21100. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21101. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21102. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21103. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21104. }
  21105. }
  21106. return parsedCustomTexture;
  21107. }
  21108. if (parsedTexture.isCube) {
  21109. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21110. }
  21111. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21112. return null;
  21113. }
  21114. var texture = BABYLON.SerializationHelper.Parse(function () {
  21115. if (parsedTexture.mirrorPlane) {
  21116. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21117. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21118. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21119. return mirrorTexture;
  21120. }
  21121. else if (parsedTexture.isRenderTarget) {
  21122. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21123. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21124. return renderTargetTexture;
  21125. }
  21126. else {
  21127. var texture;
  21128. if (parsedTexture.base64String) {
  21129. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21130. }
  21131. else {
  21132. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21133. }
  21134. return texture;
  21135. }
  21136. }, parsedTexture, scene);
  21137. // Update Sampling Mode
  21138. if (parsedTexture.samplingMode) {
  21139. var sampling = parsedTexture.samplingMode;
  21140. if (texture._samplingMode !== sampling) {
  21141. texture.updateSamplingMode(sampling);
  21142. }
  21143. }
  21144. // Animations
  21145. if (parsedTexture.animations) {
  21146. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21147. var parsedAnimation = parsedTexture.animations[animationIndex];
  21148. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21149. }
  21150. }
  21151. return texture;
  21152. };
  21153. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21154. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21155. if (noMipmap === void 0) { noMipmap = false; }
  21156. if (invertY === void 0) { invertY = true; }
  21157. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21158. if (onLoad === void 0) { onLoad = null; }
  21159. if (onError === void 0) { onError = null; }
  21160. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21161. if (name.substr(0, 5) !== "data:") {
  21162. name = "data:" + name;
  21163. }
  21164. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21165. };
  21166. // Constants
  21167. Texture.NEAREST_SAMPLINGMODE = 1;
  21168. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21169. Texture.BILINEAR_SAMPLINGMODE = 2;
  21170. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21171. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21172. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21173. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21174. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21175. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21176. Texture.NEAREST_LINEAR = 7;
  21177. Texture.NEAREST_NEAREST = 8;
  21178. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21179. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21180. Texture.LINEAR_LINEAR = 11;
  21181. Texture.LINEAR_NEAREST = 12;
  21182. Texture.EXPLICIT_MODE = 0;
  21183. Texture.SPHERICAL_MODE = 1;
  21184. Texture.PLANAR_MODE = 2;
  21185. Texture.CUBIC_MODE = 3;
  21186. Texture.PROJECTION_MODE = 4;
  21187. Texture.SKYBOX_MODE = 5;
  21188. Texture.INVCUBIC_MODE = 6;
  21189. Texture.EQUIRECTANGULAR_MODE = 7;
  21190. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21191. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21192. Texture.CLAMP_ADDRESSMODE = 0;
  21193. Texture.WRAP_ADDRESSMODE = 1;
  21194. Texture.MIRROR_ADDRESSMODE = 2;
  21195. __decorate([
  21196. BABYLON.serialize()
  21197. ], Texture.prototype, "url", void 0);
  21198. __decorate([
  21199. BABYLON.serialize()
  21200. ], Texture.prototype, "uOffset", void 0);
  21201. __decorate([
  21202. BABYLON.serialize()
  21203. ], Texture.prototype, "vOffset", void 0);
  21204. __decorate([
  21205. BABYLON.serialize()
  21206. ], Texture.prototype, "uScale", void 0);
  21207. __decorate([
  21208. BABYLON.serialize()
  21209. ], Texture.prototype, "vScale", void 0);
  21210. __decorate([
  21211. BABYLON.serialize()
  21212. ], Texture.prototype, "uAng", void 0);
  21213. __decorate([
  21214. BABYLON.serialize()
  21215. ], Texture.prototype, "vAng", void 0);
  21216. __decorate([
  21217. BABYLON.serialize()
  21218. ], Texture.prototype, "wAng", void 0);
  21219. __decorate([
  21220. BABYLON.serialize()
  21221. ], Texture.prototype, "isBlocking", null);
  21222. return Texture;
  21223. }(BABYLON.BaseTexture));
  21224. BABYLON.Texture = Texture;
  21225. })(BABYLON || (BABYLON = {}));
  21226. //# sourceMappingURL=babylon.texture.js.map
  21227. var BABYLON;
  21228. (function (BABYLON) {
  21229. var _InstancesBatch = (function () {
  21230. function _InstancesBatch() {
  21231. this.mustReturn = false;
  21232. this.visibleInstances = new Array();
  21233. this.renderSelf = new Array();
  21234. }
  21235. return _InstancesBatch;
  21236. }());
  21237. BABYLON._InstancesBatch = _InstancesBatch;
  21238. var Mesh = (function (_super) {
  21239. __extends(Mesh, _super);
  21240. /**
  21241. * @constructor
  21242. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21243. * @param {Scene} scene The scene to add this mesh to.
  21244. * @param {Node} parent The parent of this mesh, if it has one
  21245. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21246. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21247. * When false, achieved by calling a clone(), also passing False.
  21248. * This will make creation of children, recursive.
  21249. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21250. */
  21251. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21252. if (parent === void 0) { parent = null; }
  21253. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21254. var _this = _super.call(this, name, scene) || this;
  21255. // Events
  21256. /**
  21257. * An event triggered before rendering the mesh
  21258. * @type {BABYLON.Observable}
  21259. */
  21260. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21261. /**
  21262. * An event triggered after rendering the mesh
  21263. * @type {BABYLON.Observable}
  21264. */
  21265. _this.onAfterRenderObservable = new BABYLON.Observable();
  21266. /**
  21267. * An event triggered before drawing the mesh
  21268. * @type {BABYLON.Observable}
  21269. */
  21270. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21271. // Members
  21272. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21273. _this.instances = new Array();
  21274. _this._LODLevels = new Array();
  21275. _this._visibleInstances = {};
  21276. _this._renderIdForInstances = new Array();
  21277. _this._batchCache = new _InstancesBatch();
  21278. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21279. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21280. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21281. // Will be used to save a source mesh reference, If any
  21282. _this._source = null;
  21283. if (source) {
  21284. // Source mesh
  21285. _this._source = source;
  21286. // Geometry
  21287. if (source._geometry) {
  21288. source._geometry.applyToMesh(_this);
  21289. }
  21290. // Deep copy
  21291. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21292. // Parent
  21293. _this.parent = source.parent;
  21294. // Pivot
  21295. _this.setPivotMatrix(source.getPivotMatrix());
  21296. _this.id = name + "." + source.id;
  21297. // Material
  21298. _this.material = source.material;
  21299. var index;
  21300. if (!doNotCloneChildren) {
  21301. // Children
  21302. for (index = 0; index < scene.meshes.length; index++) {
  21303. var mesh = scene.meshes[index];
  21304. if (mesh.parent === source) {
  21305. // doNotCloneChildren is always going to be False
  21306. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21307. }
  21308. }
  21309. }
  21310. // Physics clone
  21311. var physicsEngine = _this.getScene().getPhysicsEngine();
  21312. if (clonePhysicsImpostor && physicsEngine) {
  21313. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21314. if (impostor) {
  21315. _this.physicsImpostor = impostor.clone(_this);
  21316. }
  21317. }
  21318. // Particles
  21319. for (index = 0; index < scene.particleSystems.length; index++) {
  21320. var system = scene.particleSystems[index];
  21321. if (system.emitter === source) {
  21322. system.clone(system.name, _this);
  21323. }
  21324. }
  21325. _this.computeWorldMatrix(true);
  21326. }
  21327. // Parent
  21328. if (parent !== null) {
  21329. _this.parent = parent;
  21330. }
  21331. return _this;
  21332. }
  21333. Object.defineProperty(Mesh, "FRONTSIDE", {
  21334. /**
  21335. * Mesh side orientation : usually the external or front surface
  21336. */
  21337. get: function () {
  21338. return Mesh._FRONTSIDE;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Mesh, "BACKSIDE", {
  21344. /**
  21345. * Mesh side orientation : usually the internal or back surface
  21346. */
  21347. get: function () {
  21348. return Mesh._BACKSIDE;
  21349. },
  21350. enumerable: true,
  21351. configurable: true
  21352. });
  21353. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21354. /**
  21355. * Mesh side orientation : both internal and external or front and back surfaces
  21356. */
  21357. get: function () {
  21358. return Mesh._DOUBLESIDE;
  21359. },
  21360. enumerable: true,
  21361. configurable: true
  21362. });
  21363. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21364. /**
  21365. * Mesh side orientation : by default, `FRONTSIDE`
  21366. */
  21367. get: function () {
  21368. return Mesh._DEFAULTSIDE;
  21369. },
  21370. enumerable: true,
  21371. configurable: true
  21372. });
  21373. Object.defineProperty(Mesh, "NO_CAP", {
  21374. /**
  21375. * Mesh cap setting : no cap
  21376. */
  21377. get: function () {
  21378. return Mesh._NO_CAP;
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Mesh, "CAP_START", {
  21384. /**
  21385. * Mesh cap setting : one cap at the beginning of the mesh
  21386. */
  21387. get: function () {
  21388. return Mesh._CAP_START;
  21389. },
  21390. enumerable: true,
  21391. configurable: true
  21392. });
  21393. Object.defineProperty(Mesh, "CAP_END", {
  21394. /**
  21395. * Mesh cap setting : one cap at the end of the mesh
  21396. */
  21397. get: function () {
  21398. return Mesh._CAP_END;
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. Object.defineProperty(Mesh, "CAP_ALL", {
  21404. /**
  21405. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21406. */
  21407. get: function () {
  21408. return Mesh._CAP_ALL;
  21409. },
  21410. enumerable: true,
  21411. configurable: true
  21412. });
  21413. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21414. set: function (callback) {
  21415. if (this._onBeforeDrawObserver) {
  21416. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21417. }
  21418. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21419. },
  21420. enumerable: true,
  21421. configurable: true
  21422. });
  21423. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21424. get: function () {
  21425. return this._morphTargetManager;
  21426. },
  21427. set: function (value) {
  21428. if (this._morphTargetManager === value) {
  21429. return;
  21430. }
  21431. this._morphTargetManager = value;
  21432. this._syncGeometryWithMorphTargetManager();
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(Mesh.prototype, "source", {
  21438. get: function () {
  21439. return this._source;
  21440. },
  21441. enumerable: true,
  21442. configurable: true
  21443. });
  21444. // Methods
  21445. /**
  21446. * Returns the string "Mesh".
  21447. */
  21448. Mesh.prototype.getClassName = function () {
  21449. return "Mesh";
  21450. };
  21451. /**
  21452. * Returns a string.
  21453. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21454. */
  21455. Mesh.prototype.toString = function (fullDetails) {
  21456. var ret = _super.prototype.toString.call(this, fullDetails);
  21457. ret += ", n vertices: " + this.getTotalVertices();
  21458. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21459. if (this.animations) {
  21460. for (var i = 0; i < this.animations.length; i++) {
  21461. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21462. }
  21463. }
  21464. if (fullDetails) {
  21465. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21466. }
  21467. return ret;
  21468. };
  21469. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21470. /**
  21471. * True if the mesh has some Levels Of Details (LOD).
  21472. * Returns a boolean.
  21473. */
  21474. get: function () {
  21475. return this._LODLevels.length > 0;
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Mesh.prototype._sortLODLevels = function () {
  21481. this._LODLevels.sort(function (a, b) {
  21482. if (a.distance < b.distance) {
  21483. return 1;
  21484. }
  21485. if (a.distance > b.distance) {
  21486. return -1;
  21487. }
  21488. return 0;
  21489. });
  21490. };
  21491. /**
  21492. * Add a mesh as LOD level triggered at the given distance.
  21493. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21494. * @param {number} distance The distance from the center of the object to show this level
  21495. * @param {Mesh} mesh The mesh to be added as LOD level
  21496. * @return {Mesh} This mesh (for chaining)
  21497. */
  21498. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21499. if (mesh && mesh._masterMesh) {
  21500. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21501. return this;
  21502. }
  21503. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21504. this._LODLevels.push(level);
  21505. if (mesh) {
  21506. mesh._masterMesh = this;
  21507. }
  21508. this._sortLODLevels();
  21509. return this;
  21510. };
  21511. /**
  21512. * Returns the LOD level mesh at the passed distance or null if not found.
  21513. * It is related to the method `addLODLevel(distance, mesh)`.
  21514. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21515. * Returns an object Mesh or `null`.
  21516. */
  21517. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21518. for (var index = 0; index < this._LODLevels.length; index++) {
  21519. var level = this._LODLevels[index];
  21520. if (level.distance === distance) {
  21521. return level.mesh;
  21522. }
  21523. }
  21524. return null;
  21525. };
  21526. /**
  21527. * Remove a mesh from the LOD array
  21528. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21529. * @param {Mesh} mesh The mesh to be removed.
  21530. * @return {Mesh} This mesh (for chaining)
  21531. */
  21532. Mesh.prototype.removeLODLevel = function (mesh) {
  21533. for (var index = 0; index < this._LODLevels.length; index++) {
  21534. if (this._LODLevels[index].mesh === mesh) {
  21535. this._LODLevels.splice(index, 1);
  21536. if (mesh) {
  21537. mesh._masterMesh = null;
  21538. }
  21539. }
  21540. }
  21541. this._sortLODLevels();
  21542. return this;
  21543. };
  21544. /**
  21545. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21546. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21547. */
  21548. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21549. if (!this._LODLevels || this._LODLevels.length === 0) {
  21550. return this;
  21551. }
  21552. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21553. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21554. if (this.onLODLevelSelection) {
  21555. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21556. }
  21557. return this;
  21558. }
  21559. for (var index = 0; index < this._LODLevels.length; index++) {
  21560. var level = this._LODLevels[index];
  21561. if (level.distance < distanceToCamera) {
  21562. if (level.mesh) {
  21563. level.mesh._preActivate();
  21564. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21565. }
  21566. if (this.onLODLevelSelection) {
  21567. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21568. }
  21569. return level.mesh;
  21570. }
  21571. }
  21572. if (this.onLODLevelSelection) {
  21573. this.onLODLevelSelection(distanceToCamera, this, this);
  21574. }
  21575. return this;
  21576. };
  21577. Object.defineProperty(Mesh.prototype, "geometry", {
  21578. /**
  21579. * Returns the mesh internal Geometry object.
  21580. */
  21581. get: function () {
  21582. return this._geometry;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. /**
  21588. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21589. */
  21590. Mesh.prototype.getTotalVertices = function () {
  21591. if (!this._geometry) {
  21592. return 0;
  21593. }
  21594. return this._geometry.getTotalVertices();
  21595. };
  21596. /**
  21597. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21598. * 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.
  21599. * You can force the copy with forceCopy === true
  21600. * Returns null if the mesh has no geometry or no vertex buffer.
  21601. * Possible `kind` values :
  21602. * - BABYLON.VertexBuffer.PositionKind
  21603. * - BABYLON.VertexBuffer.UVKind
  21604. * - BABYLON.VertexBuffer.UV2Kind
  21605. * - BABYLON.VertexBuffer.UV3Kind
  21606. * - BABYLON.VertexBuffer.UV4Kind
  21607. * - BABYLON.VertexBuffer.UV5Kind
  21608. * - BABYLON.VertexBuffer.UV6Kind
  21609. * - BABYLON.VertexBuffer.ColorKind
  21610. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21611. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21612. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21613. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21614. */
  21615. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21616. if (!this._geometry) {
  21617. return null;
  21618. }
  21619. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21620. };
  21621. /**
  21622. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21623. * Returns `undefined` if the mesh has no geometry.
  21624. * Possible `kind` values :
  21625. * - BABYLON.VertexBuffer.PositionKind
  21626. * - BABYLON.VertexBuffer.UVKind
  21627. * - BABYLON.VertexBuffer.UV2Kind
  21628. * - BABYLON.VertexBuffer.UV3Kind
  21629. * - BABYLON.VertexBuffer.UV4Kind
  21630. * - BABYLON.VertexBuffer.UV5Kind
  21631. * - BABYLON.VertexBuffer.UV6Kind
  21632. * - BABYLON.VertexBuffer.ColorKind
  21633. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21634. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21635. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21636. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21637. */
  21638. Mesh.prototype.getVertexBuffer = function (kind) {
  21639. if (!this._geometry) {
  21640. return undefined;
  21641. }
  21642. return this._geometry.getVertexBuffer(kind);
  21643. };
  21644. /**
  21645. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21646. * Possible `kind` values :
  21647. * - BABYLON.VertexBuffer.PositionKind
  21648. * - BABYLON.VertexBuffer.UVKind
  21649. * - BABYLON.VertexBuffer.UV2Kind
  21650. * - BABYLON.VertexBuffer.UV3Kind
  21651. * - BABYLON.VertexBuffer.UV4Kind
  21652. * - BABYLON.VertexBuffer.UV5Kind
  21653. * - BABYLON.VertexBuffer.UV6Kind
  21654. * - BABYLON.VertexBuffer.ColorKind
  21655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21659. */
  21660. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21661. if (!this._geometry) {
  21662. if (this._delayInfo) {
  21663. return this._delayInfo.indexOf(kind) !== -1;
  21664. }
  21665. return false;
  21666. }
  21667. return this._geometry.isVerticesDataPresent(kind);
  21668. };
  21669. /**
  21670. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21671. * Possible `kind` values :
  21672. * - BABYLON.VertexBuffer.PositionKind
  21673. * - BABYLON.VertexBuffer.UVKind
  21674. * - BABYLON.VertexBuffer.UV2Kind
  21675. * - BABYLON.VertexBuffer.UV3Kind
  21676. * - BABYLON.VertexBuffer.UV4Kind
  21677. * - BABYLON.VertexBuffer.UV5Kind
  21678. * - BABYLON.VertexBuffer.UV6Kind
  21679. * - BABYLON.VertexBuffer.ColorKind
  21680. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21681. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21682. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21683. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21684. */
  21685. Mesh.prototype.getVerticesDataKinds = function () {
  21686. if (!this._geometry) {
  21687. var result = [];
  21688. if (this._delayInfo) {
  21689. this._delayInfo.forEach(function (kind, index, array) {
  21690. result.push(kind);
  21691. });
  21692. }
  21693. return result;
  21694. }
  21695. return this._geometry.getVerticesDataKinds();
  21696. };
  21697. /**
  21698. * Returns a positive integer : the total number of indices in this mesh geometry.
  21699. * Returns zero if the mesh has no geometry.
  21700. */
  21701. Mesh.prototype.getTotalIndices = function () {
  21702. if (!this._geometry) {
  21703. return 0;
  21704. }
  21705. return this._geometry.getTotalIndices();
  21706. };
  21707. /**
  21708. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21709. * 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.
  21710. * Returns an empty array if the mesh has no geometry.
  21711. */
  21712. Mesh.prototype.getIndices = function (copyWhenShared) {
  21713. if (!this._geometry) {
  21714. return [];
  21715. }
  21716. return this._geometry.getIndices(copyWhenShared);
  21717. };
  21718. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21719. get: function () {
  21720. return this._masterMesh !== null && this._masterMesh !== undefined;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. /**
  21726. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21727. */
  21728. Mesh.prototype.isReady = function () {
  21729. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21730. return false;
  21731. }
  21732. return _super.prototype.isReady.call(this);
  21733. };
  21734. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21735. get: function () {
  21736. return this._sideOrientation;
  21737. },
  21738. /**
  21739. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21740. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21741. */
  21742. set: function (sideO) {
  21743. this._sideOrientation = sideO;
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21749. /**
  21750. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21751. * This property is pertinent only for updatable parametric shapes.
  21752. */
  21753. get: function () {
  21754. return this._areNormalsFrozen;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. /**
  21760. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21761. * It has no effect at all on other shapes.
  21762. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21763. * Returns the Mesh.
  21764. */
  21765. Mesh.prototype.freezeNormals = function () {
  21766. this._areNormalsFrozen = true;
  21767. return this;
  21768. };
  21769. /**
  21770. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21771. * It has no effect at all on other shapes.
  21772. * It reactivates the mesh normals computation if it was previously frozen.
  21773. * Returns the Mesh.
  21774. */
  21775. Mesh.prototype.unfreezeNormals = function () {
  21776. this._areNormalsFrozen = false;
  21777. return this;
  21778. };
  21779. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21780. /**
  21781. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21782. */
  21783. set: function (count) {
  21784. this._overridenInstanceCount = count;
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. // Methods
  21790. Mesh.prototype._preActivate = function () {
  21791. var sceneRenderId = this.getScene().getRenderId();
  21792. if (this._preActivateId === sceneRenderId) {
  21793. return this;
  21794. }
  21795. this._preActivateId = sceneRenderId;
  21796. this._visibleInstances = null;
  21797. return this;
  21798. };
  21799. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21800. if (this._visibleInstances) {
  21801. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21802. }
  21803. return this;
  21804. };
  21805. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21806. if (!this._visibleInstances) {
  21807. this._visibleInstances = {};
  21808. this._visibleInstances.defaultRenderId = renderId;
  21809. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21810. }
  21811. if (!this._visibleInstances[renderId]) {
  21812. this._visibleInstances[renderId] = new Array();
  21813. }
  21814. this._visibleInstances[renderId].push(instance);
  21815. return this;
  21816. };
  21817. /**
  21818. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21819. * This means the mesh underlying bounding box and sphere are recomputed.
  21820. * Returns the Mesh.
  21821. */
  21822. Mesh.prototype.refreshBoundingInfo = function () {
  21823. if (this._boundingInfo.isLocked) {
  21824. return;
  21825. }
  21826. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21827. if (data) {
  21828. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21829. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21830. }
  21831. if (this.subMeshes) {
  21832. for (var index = 0; index < this.subMeshes.length; index++) {
  21833. this.subMeshes[index].refreshBoundingInfo();
  21834. }
  21835. }
  21836. this._updateBoundingInfo();
  21837. return this;
  21838. };
  21839. Mesh.prototype._createGlobalSubMesh = function (force) {
  21840. var totalVertices = this.getTotalVertices();
  21841. if (!totalVertices || !this.getIndices()) {
  21842. return null;
  21843. }
  21844. // Check if we need to recreate the submeshes
  21845. if (this.subMeshes && this.subMeshes.length > 0) {
  21846. var totalIndices = this.getIndices().length;
  21847. var needToRecreate = false;
  21848. if (force) {
  21849. needToRecreate = true;
  21850. }
  21851. else {
  21852. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21853. var submesh = _a[_i];
  21854. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21855. needToRecreate = true;
  21856. break;
  21857. }
  21858. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21859. needToRecreate = true;
  21860. break;
  21861. }
  21862. }
  21863. }
  21864. if (!needToRecreate) {
  21865. return;
  21866. }
  21867. }
  21868. this.releaseSubMeshes();
  21869. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21870. };
  21871. Mesh.prototype.subdivide = function (count) {
  21872. if (count < 1) {
  21873. return;
  21874. }
  21875. var totalIndices = this.getTotalIndices();
  21876. var subdivisionSize = (totalIndices / count) | 0;
  21877. var offset = 0;
  21878. // Ensure that subdivisionSize is a multiple of 3
  21879. while (subdivisionSize % 3 !== 0) {
  21880. subdivisionSize++;
  21881. }
  21882. this.releaseSubMeshes();
  21883. for (var index = 0; index < count; index++) {
  21884. if (offset >= totalIndices) {
  21885. break;
  21886. }
  21887. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21888. offset += subdivisionSize;
  21889. }
  21890. this.synchronizeInstances();
  21891. };
  21892. /**
  21893. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21894. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21895. * The `data` are either a numeric array either a Float32Array.
  21896. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21897. * 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).
  21898. * Note that a new underlying VertexBuffer object is created each call.
  21899. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21900. *
  21901. * Possible `kind` values :
  21902. * - BABYLON.VertexBuffer.PositionKind
  21903. * - BABYLON.VertexBuffer.UVKind
  21904. * - BABYLON.VertexBuffer.UV2Kind
  21905. * - BABYLON.VertexBuffer.UV3Kind
  21906. * - BABYLON.VertexBuffer.UV4Kind
  21907. * - BABYLON.VertexBuffer.UV5Kind
  21908. * - BABYLON.VertexBuffer.UV6Kind
  21909. * - BABYLON.VertexBuffer.ColorKind
  21910. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21911. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21912. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21913. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21914. *
  21915. * Returns the Mesh.
  21916. */
  21917. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21918. if (!this._geometry) {
  21919. var vertexData = new BABYLON.VertexData();
  21920. vertexData.set(data, kind);
  21921. var scene = this.getScene();
  21922. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21923. }
  21924. else {
  21925. this._geometry.setVerticesData(kind, data, updatable, stride);
  21926. }
  21927. return this;
  21928. };
  21929. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21930. if (updatable === void 0) { updatable = true; }
  21931. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21932. return;
  21933. }
  21934. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21935. };
  21936. /**
  21937. * Sets the mesh VertexBuffer.
  21938. * Returns the Mesh.
  21939. */
  21940. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21941. if (!this._geometry) {
  21942. var scene = this.getScene();
  21943. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21944. }
  21945. this._geometry.setVerticesBuffer(buffer);
  21946. return this;
  21947. };
  21948. /**
  21949. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21950. * If the mesh has no geometry, it is simply returned as it is.
  21951. * The `data` are either a numeric array either a Float32Array.
  21952. * No new underlying VertexBuffer object is created.
  21953. * 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.
  21954. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21955. *
  21956. * Possible `kind` values :
  21957. * - BABYLON.VertexBuffer.PositionKind
  21958. * - BABYLON.VertexBuffer.UVKind
  21959. * - BABYLON.VertexBuffer.UV2Kind
  21960. * - BABYLON.VertexBuffer.UV3Kind
  21961. * - BABYLON.VertexBuffer.UV4Kind
  21962. * - BABYLON.VertexBuffer.UV5Kind
  21963. * - BABYLON.VertexBuffer.UV6Kind
  21964. * - BABYLON.VertexBuffer.ColorKind
  21965. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21966. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21967. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21968. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21969. *
  21970. * Returns the Mesh.
  21971. */
  21972. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21973. if (!this._geometry) {
  21974. return;
  21975. }
  21976. if (!makeItUnique) {
  21977. this._geometry.updateVerticesData(kind, data, updateExtends);
  21978. }
  21979. else {
  21980. this.makeGeometryUnique();
  21981. this.updateVerticesData(kind, data, updateExtends, false);
  21982. }
  21983. return this;
  21984. };
  21985. /**
  21986. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21987. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21988. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21989. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21990. * Returns the Mesh.
  21991. */
  21992. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21993. if (computeNormals === void 0) { computeNormals = true; }
  21994. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21995. positionFunction(positions);
  21996. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21997. if (computeNormals) {
  21998. var indices = this.getIndices();
  21999. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22000. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22001. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22002. }
  22003. return this;
  22004. };
  22005. /**
  22006. * Creates a un-shared specific occurence of the geometry for the mesh.
  22007. * Returns the Mesh.
  22008. */
  22009. Mesh.prototype.makeGeometryUnique = function () {
  22010. if (!this._geometry) {
  22011. return;
  22012. }
  22013. var oldGeometry = this._geometry;
  22014. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22015. oldGeometry.releaseForMesh(this, true);
  22016. geometry.applyToMesh(this);
  22017. return this;
  22018. };
  22019. /**
  22020. * Sets the mesh indices.
  22021. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22022. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22023. * This method creates a new index buffer each call.
  22024. * Returns the Mesh.
  22025. */
  22026. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22027. if (!this._geometry) {
  22028. var vertexData = new BABYLON.VertexData();
  22029. vertexData.indices = indices;
  22030. var scene = this.getScene();
  22031. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22032. }
  22033. else {
  22034. this._geometry.setIndices(indices, totalVertices);
  22035. }
  22036. return this;
  22037. };
  22038. /**
  22039. * Invert the geometry to move from a right handed system to a left handed one.
  22040. * Returns the Mesh.
  22041. */
  22042. Mesh.prototype.toLeftHanded = function () {
  22043. if (!this._geometry) {
  22044. return;
  22045. }
  22046. this._geometry.toLeftHanded();
  22047. return this;
  22048. };
  22049. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22050. var engine = this.getScene().getEngine();
  22051. // Wireframe
  22052. var indexToBind;
  22053. if (this._unIndexed) {
  22054. indexToBind = null;
  22055. }
  22056. else {
  22057. switch (fillMode) {
  22058. case BABYLON.Material.PointFillMode:
  22059. indexToBind = null;
  22060. break;
  22061. case BABYLON.Material.WireFrameFillMode:
  22062. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22063. break;
  22064. default:
  22065. case BABYLON.Material.TriangleFillMode:
  22066. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22067. break;
  22068. }
  22069. }
  22070. // VBOs
  22071. this._geometry._bind(effect, indexToBind);
  22072. return this;
  22073. };
  22074. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22075. if (alternate === void 0) { alternate = false; }
  22076. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22077. return this;
  22078. }
  22079. this.onBeforeDrawObservable.notifyObservers(this);
  22080. var scene = this.getScene();
  22081. var engine = scene.getEngine();
  22082. // Draw order
  22083. switch (fillMode) {
  22084. case BABYLON.Material.PointFillMode:
  22085. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22086. break;
  22087. case BABYLON.Material.WireFrameFillMode:
  22088. if (this._unIndexed) {
  22089. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22090. }
  22091. else {
  22092. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22093. }
  22094. break;
  22095. default:
  22096. if (this._unIndexed) {
  22097. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22098. }
  22099. else {
  22100. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22101. }
  22102. }
  22103. if (scene._isAlternateRenderingEnabled && !alternate) {
  22104. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22105. scene._switchToAlternateCameraConfiguration(true);
  22106. this._effectiveMaterial.bindView(effect);
  22107. this._effectiveMaterial.bindViewProjection(effect);
  22108. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22109. this._draw(subMesh, fillMode, instancesCount, true);
  22110. engine.setViewport(scene.activeCamera.viewport);
  22111. scene._switchToAlternateCameraConfiguration(false);
  22112. this._effectiveMaterial.bindView(effect);
  22113. this._effectiveMaterial.bindViewProjection(effect);
  22114. }
  22115. return this;
  22116. };
  22117. /**
  22118. * Registers for this mesh a javascript function called just before the rendering process.
  22119. * This function is passed the current mesh.
  22120. * Return the Mesh.
  22121. */
  22122. Mesh.prototype.registerBeforeRender = function (func) {
  22123. this.onBeforeRenderObservable.add(func);
  22124. return this;
  22125. };
  22126. /**
  22127. * Disposes a previously registered javascript function called before the rendering.
  22128. * This function is passed the current mesh.
  22129. * Returns the Mesh.
  22130. */
  22131. Mesh.prototype.unregisterBeforeRender = function (func) {
  22132. this.onBeforeRenderObservable.removeCallback(func);
  22133. return this;
  22134. };
  22135. /**
  22136. * Registers for this mesh a javascript function called just after the rendering is complete.
  22137. * This function is passed the current mesh.
  22138. * Returns the Mesh.
  22139. */
  22140. Mesh.prototype.registerAfterRender = function (func) {
  22141. this.onAfterRenderObservable.add(func);
  22142. return this;
  22143. };
  22144. /**
  22145. * Disposes a previously registered javascript function called after the rendering.
  22146. * This function is passed the current mesh.
  22147. * Return the Mesh.
  22148. */
  22149. Mesh.prototype.unregisterAfterRender = function (func) {
  22150. this.onAfterRenderObservable.removeCallback(func);
  22151. return this;
  22152. };
  22153. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22154. var scene = this.getScene();
  22155. this._batchCache.mustReturn = false;
  22156. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22157. this._batchCache.visibleInstances[subMeshId] = null;
  22158. if (this._visibleInstances) {
  22159. var currentRenderId = scene.getRenderId();
  22160. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22161. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22162. var selfRenderId = this._renderId;
  22163. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22164. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22165. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22166. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22167. }
  22168. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22169. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22170. this._batchCache.mustReturn = true;
  22171. return this._batchCache;
  22172. }
  22173. if (currentRenderId !== selfRenderId) {
  22174. this._batchCache.renderSelf[subMeshId] = false;
  22175. }
  22176. }
  22177. this._renderIdForInstances[subMeshId] = currentRenderId;
  22178. }
  22179. return this._batchCache;
  22180. };
  22181. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22182. var visibleInstances = batch.visibleInstances[subMesh._id];
  22183. var matricesCount = visibleInstances.length + 1;
  22184. var bufferSize = matricesCount * 16 * 4;
  22185. var currentInstancesBufferSize = this._instancesBufferSize;
  22186. var instancesBuffer = this._instancesBuffer;
  22187. while (this._instancesBufferSize < bufferSize) {
  22188. this._instancesBufferSize *= 2;
  22189. }
  22190. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22191. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22192. }
  22193. var offset = 0;
  22194. var instancesCount = 0;
  22195. var world = this.getWorldMatrix();
  22196. if (batch.renderSelf[subMesh._id]) {
  22197. world.copyToArray(this._instancesData, offset);
  22198. offset += 16;
  22199. instancesCount++;
  22200. }
  22201. if (visibleInstances) {
  22202. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22203. var instance = visibleInstances[instanceIndex];
  22204. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22205. offset += 16;
  22206. instancesCount++;
  22207. }
  22208. }
  22209. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22210. if (instancesBuffer) {
  22211. instancesBuffer.dispose();
  22212. }
  22213. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22214. this._instancesBuffer = instancesBuffer;
  22215. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22216. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22217. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22218. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22219. }
  22220. else {
  22221. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22222. }
  22223. this._bind(subMesh, effect, fillMode);
  22224. this._draw(subMesh, fillMode, instancesCount);
  22225. engine.unbindInstanceAttributes();
  22226. return this;
  22227. };
  22228. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22229. var scene = this.getScene();
  22230. var engine = scene.getEngine();
  22231. if (hardwareInstancedRendering) {
  22232. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22233. }
  22234. else {
  22235. if (batch.renderSelf[subMesh._id]) {
  22236. // Draw
  22237. if (onBeforeDraw) {
  22238. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22239. }
  22240. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22241. }
  22242. if (batch.visibleInstances[subMesh._id]) {
  22243. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22244. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22245. // World
  22246. var world = instance.getWorldMatrix();
  22247. if (onBeforeDraw) {
  22248. onBeforeDraw(true, world, effectiveMaterial);
  22249. }
  22250. // Draw
  22251. this._draw(subMesh, fillMode);
  22252. }
  22253. }
  22254. }
  22255. return this;
  22256. };
  22257. /**
  22258. * Triggers the draw call for the mesh.
  22259. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22260. * Returns the Mesh.
  22261. */
  22262. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22263. this.checkOcclusionQuery();
  22264. if (this._isOccluded) {
  22265. return;
  22266. }
  22267. var scene = this.getScene();
  22268. // Managing instances
  22269. var batch = this._getInstancesRenderList(subMesh._id);
  22270. if (batch.mustReturn) {
  22271. return this;
  22272. }
  22273. // Checking geometry state
  22274. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22275. return this;
  22276. }
  22277. var callbackIndex;
  22278. this.onBeforeRenderObservable.notifyObservers(this);
  22279. var engine = scene.getEngine();
  22280. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22281. // Material
  22282. this._effectiveMaterial = subMesh.getMaterial();
  22283. if (!this._effectiveMaterial) {
  22284. return this;
  22285. }
  22286. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22287. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22288. return this;
  22289. }
  22290. }
  22291. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22292. return this;
  22293. }
  22294. // Alpha mode
  22295. if (enableAlphaMode) {
  22296. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22297. }
  22298. // Outline - step 1
  22299. var savedDepthWrite = engine.getDepthWrite();
  22300. if (this.renderOutline) {
  22301. engine.setDepthWrite(false);
  22302. scene.getOutlineRenderer().render(subMesh, batch);
  22303. engine.setDepthWrite(savedDepthWrite);
  22304. }
  22305. var effect;
  22306. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22307. effect = subMesh.effect;
  22308. }
  22309. else {
  22310. effect = this._effectiveMaterial.getEffect();
  22311. }
  22312. this._effectiveMaterial._preBind(effect);
  22313. // Bind
  22314. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22315. if (!hardwareInstancedRendering) {
  22316. this._bind(subMesh, effect, fillMode);
  22317. }
  22318. var world = this.getWorldMatrix();
  22319. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22320. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22321. }
  22322. else {
  22323. this._effectiveMaterial.bind(world, this);
  22324. }
  22325. // Draw
  22326. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22327. // Unbind
  22328. this._effectiveMaterial.unbind();
  22329. // Outline - step 2
  22330. if (this.renderOutline && savedDepthWrite) {
  22331. engine.setDepthWrite(true);
  22332. engine.setColorWrite(false);
  22333. scene.getOutlineRenderer().render(subMesh, batch);
  22334. engine.setColorWrite(true);
  22335. }
  22336. // Overlay
  22337. if (this.renderOverlay) {
  22338. var currentMode = engine.getAlphaMode();
  22339. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22340. scene.getOutlineRenderer().render(subMesh, batch, true);
  22341. engine.setAlphaMode(currentMode);
  22342. }
  22343. this.onAfterRenderObservable.notifyObservers(this);
  22344. return this;
  22345. };
  22346. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22347. if (isInstance) {
  22348. effectiveMaterial.bindOnlyWorldMatrix(world);
  22349. }
  22350. return this;
  22351. };
  22352. /**
  22353. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22354. */
  22355. Mesh.prototype.getEmittedParticleSystems = function () {
  22356. var results = new Array();
  22357. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22358. var particleSystem = this.getScene().particleSystems[index];
  22359. if (particleSystem.emitter === this) {
  22360. results.push(particleSystem);
  22361. }
  22362. }
  22363. return results;
  22364. };
  22365. /**
  22366. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22367. */
  22368. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22369. var results = new Array();
  22370. var descendants = this.getDescendants();
  22371. descendants.push(this);
  22372. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22373. var particleSystem = this.getScene().particleSystems[index];
  22374. var emitter = particleSystem.emitter;
  22375. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22376. results.push(particleSystem);
  22377. }
  22378. }
  22379. return results;
  22380. };
  22381. Mesh.prototype._checkDelayState = function () {
  22382. var scene = this.getScene();
  22383. if (this._geometry) {
  22384. this._geometry.load(scene);
  22385. }
  22386. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22388. this._queueLoad(this, scene);
  22389. }
  22390. return this;
  22391. };
  22392. Mesh.prototype._queueLoad = function (mesh, scene) {
  22393. var _this = this;
  22394. scene._addPendingData(mesh);
  22395. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22396. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22397. if (data instanceof ArrayBuffer) {
  22398. _this._delayLoadingFunction(data, _this);
  22399. }
  22400. else {
  22401. _this._delayLoadingFunction(JSON.parse(data), _this);
  22402. }
  22403. _this.instances.forEach(function (instance) {
  22404. instance._syncSubMeshes();
  22405. });
  22406. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22407. scene._removePendingData(_this);
  22408. }, function () { }, scene.database, getBinaryData);
  22409. return this;
  22410. };
  22411. /**
  22412. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22413. */
  22414. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22415. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22416. return false;
  22417. }
  22418. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22419. return false;
  22420. }
  22421. this._checkDelayState();
  22422. return true;
  22423. };
  22424. /**
  22425. * Sets the mesh material by the material or multiMaterial `id` property.
  22426. * The material `id` is a string identifying the material or the multiMaterial.
  22427. * This method returns the Mesh.
  22428. */
  22429. Mesh.prototype.setMaterialByID = function (id) {
  22430. var materials = this.getScene().materials;
  22431. var index;
  22432. for (index = materials.length - 1; index > -1; index--) {
  22433. if (materials[index].id === id) {
  22434. this.material = materials[index];
  22435. return this;
  22436. }
  22437. }
  22438. // Multi
  22439. var multiMaterials = this.getScene().multiMaterials;
  22440. for (index = multiMaterials.length - 1; index > -1; index--) {
  22441. if (multiMaterials[index].id === id) {
  22442. this.material = multiMaterials[index];
  22443. return this;
  22444. }
  22445. }
  22446. return this;
  22447. };
  22448. /**
  22449. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22450. */
  22451. Mesh.prototype.getAnimatables = function () {
  22452. var results = [];
  22453. if (this.material) {
  22454. results.push(this.material);
  22455. }
  22456. if (this.skeleton) {
  22457. results.push(this.skeleton);
  22458. }
  22459. return results;
  22460. };
  22461. /**
  22462. * Modifies the mesh geometry according to the passed transformation matrix.
  22463. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22464. * The mesh normals are modified accordingly the same transformation.
  22465. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22466. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22467. * Returns the Mesh.
  22468. */
  22469. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22470. // Position
  22471. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22472. return this;
  22473. }
  22474. var submeshes = this.subMeshes.splice(0);
  22475. this._resetPointsArrayCache();
  22476. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22477. var temp = [];
  22478. var index;
  22479. for (index = 0; index < data.length; index += 3) {
  22480. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22481. }
  22482. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22483. // Normals
  22484. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22485. return this;
  22486. }
  22487. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22488. temp = [];
  22489. for (index = 0; index < data.length; index += 3) {
  22490. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22491. }
  22492. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22493. // flip faces?
  22494. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22495. this.flipFaces();
  22496. }
  22497. // Restore submeshes
  22498. this.releaseSubMeshes();
  22499. this.subMeshes = submeshes;
  22500. return this;
  22501. };
  22502. /**
  22503. * Modifies the mesh geometry according to its own current World Matrix.
  22504. * The mesh World Matrix is then reset.
  22505. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22506. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22507. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22508. * Returns the Mesh.
  22509. */
  22510. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22511. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22512. this.scaling.copyFromFloats(1, 1, 1);
  22513. this.position.copyFromFloats(0, 0, 0);
  22514. this.rotation.copyFromFloats(0, 0, 0);
  22515. //only if quaternion is already set
  22516. if (this.rotationQuaternion) {
  22517. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22518. }
  22519. this._worldMatrix = BABYLON.Matrix.Identity();
  22520. return this;
  22521. };
  22522. Object.defineProperty(Mesh.prototype, "_positions", {
  22523. // Cache
  22524. get: function () {
  22525. if (this._geometry) {
  22526. return this._geometry._positions;
  22527. }
  22528. return null;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Mesh.prototype._resetPointsArrayCache = function () {
  22534. if (this._geometry) {
  22535. this._geometry._resetPointsArrayCache();
  22536. }
  22537. return this;
  22538. };
  22539. Mesh.prototype._generatePointsArray = function () {
  22540. if (this._geometry) {
  22541. return this._geometry._generatePointsArray();
  22542. }
  22543. return false;
  22544. };
  22545. /**
  22546. * Returns a new Mesh object generated from the current mesh properties.
  22547. * This method must not get confused with createInstance().
  22548. * The parameter `name` is a string, the name given to the new mesh.
  22549. * The optional parameter `newParent` can be any Node object (default `null`).
  22550. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22551. * 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.
  22552. */
  22553. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22554. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22555. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22556. };
  22557. /**
  22558. * Disposes the mesh.
  22559. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22560. */
  22561. Mesh.prototype.dispose = function (doNotRecurse) {
  22562. var _this = this;
  22563. this.morphTargetManager = undefined;
  22564. if (this._geometry) {
  22565. this._geometry.releaseForMesh(this, true);
  22566. }
  22567. // Sources
  22568. var meshes = this.getScene().meshes;
  22569. meshes.forEach(function (mesh) {
  22570. if (mesh._source && mesh._source === _this) {
  22571. mesh._source = null;
  22572. }
  22573. });
  22574. this._source = null;
  22575. // Instances
  22576. if (this._instancesBuffer) {
  22577. this._instancesBuffer.dispose();
  22578. this._instancesBuffer = null;
  22579. }
  22580. while (this.instances.length) {
  22581. this.instances[0].dispose();
  22582. }
  22583. // Highlight layers.
  22584. var highlightLayers = this.getScene().highlightLayers;
  22585. for (var i = 0; i < highlightLayers.length; i++) {
  22586. var highlightLayer = highlightLayers[i];
  22587. if (highlightLayer) {
  22588. highlightLayer.removeMesh(this);
  22589. highlightLayer.removeExcludedMesh(this);
  22590. }
  22591. }
  22592. _super.prototype.dispose.call(this, doNotRecurse);
  22593. };
  22594. /**
  22595. * Modifies the mesh geometry according to a displacement map.
  22596. * 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.
  22597. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22598. * This method returns nothing.
  22599. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22600. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22601. * 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.
  22602. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22603. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22604. *
  22605. * Returns the Mesh.
  22606. */
  22607. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22608. var _this = this;
  22609. var scene = this.getScene();
  22610. var onload = function (img) {
  22611. // Getting height map data
  22612. var canvas = document.createElement("canvas");
  22613. var context = canvas.getContext("2d");
  22614. var heightMapWidth = img.width;
  22615. var heightMapHeight = img.height;
  22616. canvas.width = heightMapWidth;
  22617. canvas.height = heightMapHeight;
  22618. context.drawImage(img, 0, 0);
  22619. // Create VertexData from map data
  22620. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22621. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22622. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22623. //execute success callback, if set
  22624. if (onSuccess) {
  22625. onSuccess(_this);
  22626. }
  22627. };
  22628. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22629. return this;
  22630. };
  22631. /**
  22632. * Modifies the mesh geometry according to a displacementMap buffer.
  22633. * 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.
  22634. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22635. * This method returns nothing.
  22636. * 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.
  22637. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22638. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22639. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22640. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22641. *
  22642. * Returns the Mesh.
  22643. */
  22644. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22645. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22646. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22647. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22648. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22649. return this;
  22650. }
  22651. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22652. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22653. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22654. var position = BABYLON.Vector3.Zero();
  22655. var normal = BABYLON.Vector3.Zero();
  22656. var uv = BABYLON.Vector2.Zero();
  22657. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22658. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22659. for (var index = 0; index < positions.length; index += 3) {
  22660. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22661. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22662. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22663. // Compute height
  22664. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22665. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22666. var pos = (u + v * heightMapWidth) * 4;
  22667. var r = buffer[pos] / 255.0;
  22668. var g = buffer[pos + 1] / 255.0;
  22669. var b = buffer[pos + 2] / 255.0;
  22670. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22671. normal.normalize();
  22672. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22673. position = position.add(normal);
  22674. position.toArray(positions, index);
  22675. }
  22676. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22677. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22678. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22679. return this;
  22680. };
  22681. /**
  22682. * Modify the mesh to get a flat shading rendering.
  22683. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22684. * This method returns the Mesh.
  22685. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22686. */
  22687. Mesh.prototype.convertToFlatShadedMesh = function () {
  22688. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22689. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22690. var kinds = this.getVerticesDataKinds();
  22691. var vbs = [];
  22692. var data = [];
  22693. var newdata = [];
  22694. var updatableNormals = false;
  22695. var kindIndex;
  22696. var kind;
  22697. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22698. kind = kinds[kindIndex];
  22699. var vertexBuffer = this.getVertexBuffer(kind);
  22700. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22701. updatableNormals = vertexBuffer.isUpdatable();
  22702. kinds.splice(kindIndex, 1);
  22703. kindIndex--;
  22704. continue;
  22705. }
  22706. vbs[kind] = vertexBuffer;
  22707. data[kind] = vbs[kind].getData();
  22708. newdata[kind] = [];
  22709. }
  22710. // Save previous submeshes
  22711. var previousSubmeshes = this.subMeshes.slice(0);
  22712. var indices = this.getIndices();
  22713. var totalIndices = this.getTotalIndices();
  22714. // Generating unique vertices per face
  22715. var index;
  22716. for (index = 0; index < totalIndices; index++) {
  22717. var vertexIndex = indices[index];
  22718. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22719. kind = kinds[kindIndex];
  22720. var stride = vbs[kind].getStrideSize();
  22721. for (var offset = 0; offset < stride; offset++) {
  22722. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22723. }
  22724. }
  22725. }
  22726. // Updating faces & normal
  22727. var normals = [];
  22728. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22729. for (index = 0; index < totalIndices; index += 3) {
  22730. indices[index] = index;
  22731. indices[index + 1] = index + 1;
  22732. indices[index + 2] = index + 2;
  22733. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22734. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22735. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22736. var p1p2 = p1.subtract(p2);
  22737. var p3p2 = p3.subtract(p2);
  22738. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22739. // Store same normals for every vertex
  22740. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22741. normals.push(normal.x);
  22742. normals.push(normal.y);
  22743. normals.push(normal.z);
  22744. }
  22745. }
  22746. this.setIndices(indices);
  22747. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22748. // Updating vertex buffers
  22749. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22750. kind = kinds[kindIndex];
  22751. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22752. }
  22753. // Updating submeshes
  22754. this.releaseSubMeshes();
  22755. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22756. var previousOne = previousSubmeshes[submeshIndex];
  22757. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22758. }
  22759. this.synchronizeInstances();
  22760. return this;
  22761. };
  22762. /**
  22763. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22764. * In other words, more vertices, no more indices and a single bigger VBO.
  22765. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22766. * Returns the Mesh.
  22767. */
  22768. Mesh.prototype.convertToUnIndexedMesh = function () {
  22769. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22770. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22771. var kinds = this.getVerticesDataKinds();
  22772. var vbs = [];
  22773. var data = [];
  22774. var newdata = [];
  22775. var updatableNormals = false;
  22776. var kindIndex;
  22777. var kind;
  22778. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22779. kind = kinds[kindIndex];
  22780. var vertexBuffer = this.getVertexBuffer(kind);
  22781. vbs[kind] = vertexBuffer;
  22782. data[kind] = vbs[kind].getData();
  22783. newdata[kind] = [];
  22784. }
  22785. // Save previous submeshes
  22786. var previousSubmeshes = this.subMeshes.slice(0);
  22787. var indices = this.getIndices();
  22788. var totalIndices = this.getTotalIndices();
  22789. // Generating unique vertices per face
  22790. var index;
  22791. for (index = 0; index < totalIndices; index++) {
  22792. var vertexIndex = indices[index];
  22793. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22794. kind = kinds[kindIndex];
  22795. var stride = vbs[kind].getStrideSize();
  22796. for (var offset = 0; offset < stride; offset++) {
  22797. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22798. }
  22799. }
  22800. }
  22801. // Updating indices
  22802. for (index = 0; index < totalIndices; index += 3) {
  22803. indices[index] = index;
  22804. indices[index + 1] = index + 1;
  22805. indices[index + 2] = index + 2;
  22806. }
  22807. this.setIndices(indices);
  22808. // Updating vertex buffers
  22809. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22810. kind = kinds[kindIndex];
  22811. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22812. }
  22813. // Updating submeshes
  22814. this.releaseSubMeshes();
  22815. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22816. var previousOne = previousSubmeshes[submeshIndex];
  22817. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22818. }
  22819. this._unIndexed = true;
  22820. this.synchronizeInstances();
  22821. return this;
  22822. };
  22823. /**
  22824. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22825. * This method returns the Mesh.
  22826. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22827. */
  22828. Mesh.prototype.flipFaces = function (flipNormals) {
  22829. if (flipNormals === void 0) { flipNormals = false; }
  22830. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22831. var i;
  22832. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22833. for (i = 0; i < vertex_data.normals.length; i++) {
  22834. vertex_data.normals[i] *= -1;
  22835. }
  22836. }
  22837. var temp;
  22838. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22839. // reassign indices
  22840. temp = vertex_data.indices[i + 1];
  22841. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22842. vertex_data.indices[i + 2] = temp;
  22843. }
  22844. vertex_data.applyToMesh(this);
  22845. return this;
  22846. };
  22847. // Instances
  22848. /**
  22849. * Creates a new InstancedMesh object from the mesh model.
  22850. * An instance shares the same properties and the same material than its model.
  22851. * Only these properties of each instance can then be set individually :
  22852. * - position
  22853. * - rotation
  22854. * - rotationQuaternion
  22855. * - setPivotMatrix
  22856. * - scaling
  22857. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22858. * Warning : this method is not supported for Line mesh and LineSystem
  22859. */
  22860. Mesh.prototype.createInstance = function (name) {
  22861. return new BABYLON.InstancedMesh(name, this);
  22862. };
  22863. /**
  22864. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22865. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22866. * This method returns the Mesh.
  22867. */
  22868. Mesh.prototype.synchronizeInstances = function () {
  22869. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22870. var instance = this.instances[instanceIndex];
  22871. instance._syncSubMeshes();
  22872. }
  22873. return this;
  22874. };
  22875. /**
  22876. * Simplify the mesh according to the given array of settings.
  22877. * Function will return immediately and will simplify async. It returns the Mesh.
  22878. * @param settings a collection of simplification settings.
  22879. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22880. * @param type the type of simplification to run.
  22881. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22882. */
  22883. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22884. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22885. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22886. this.getScene().simplificationQueue.addTask({
  22887. settings: settings,
  22888. parallelProcessing: parallelProcessing,
  22889. mesh: this,
  22890. simplificationType: simplificationType,
  22891. successCallback: successCallback
  22892. });
  22893. return this;
  22894. };
  22895. /**
  22896. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22897. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22898. * This should be used together with the simplification to avoid disappearing triangles.
  22899. * Returns the Mesh.
  22900. * @param successCallback an optional success callback to be called after the optimization finished.
  22901. */
  22902. Mesh.prototype.optimizeIndices = function (successCallback) {
  22903. var _this = this;
  22904. var indices = this.getIndices();
  22905. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22906. var vectorPositions = [];
  22907. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22908. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22909. }
  22910. var dupes = [];
  22911. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22912. var realPos = vectorPositions.length - 1 - iteration;
  22913. var testedPosition = vectorPositions[realPos];
  22914. for (var j = 0; j < realPos; ++j) {
  22915. var againstPosition = vectorPositions[j];
  22916. if (testedPosition.equals(againstPosition)) {
  22917. dupes[realPos] = j;
  22918. break;
  22919. }
  22920. }
  22921. }, function () {
  22922. for (var i = 0; i < indices.length; ++i) {
  22923. indices[i] = dupes[indices[i]] || indices[i];
  22924. }
  22925. //indices are now reordered
  22926. var originalSubMeshes = _this.subMeshes.slice(0);
  22927. _this.setIndices(indices);
  22928. _this.subMeshes = originalSubMeshes;
  22929. if (successCallback) {
  22930. successCallback(_this);
  22931. }
  22932. });
  22933. return this;
  22934. };
  22935. Mesh.prototype.serialize = function (serializationObject) {
  22936. serializationObject.name = this.name;
  22937. serializationObject.id = this.id;
  22938. serializationObject.type = this.getClassName();
  22939. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22940. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22941. }
  22942. serializationObject.position = this.position.asArray();
  22943. if (this.rotationQuaternion) {
  22944. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22945. }
  22946. else if (this.rotation) {
  22947. serializationObject.rotation = this.rotation.asArray();
  22948. }
  22949. serializationObject.scaling = this.scaling.asArray();
  22950. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22951. serializationObject.isEnabled = this.isEnabled();
  22952. serializationObject.isVisible = this.isVisible;
  22953. serializationObject.infiniteDistance = this.infiniteDistance;
  22954. serializationObject.pickable = this.isPickable;
  22955. serializationObject.receiveShadows = this.receiveShadows;
  22956. serializationObject.billboardMode = this.billboardMode;
  22957. serializationObject.visibility = this.visibility;
  22958. serializationObject.checkCollisions = this.checkCollisions;
  22959. serializationObject.isBlocker = this.isBlocker;
  22960. // Parent
  22961. if (this.parent) {
  22962. serializationObject.parentId = this.parent.id;
  22963. }
  22964. // Geometry
  22965. var geometry = this._geometry;
  22966. if (geometry) {
  22967. var geometryId = geometry.id;
  22968. serializationObject.geometryId = geometryId;
  22969. // SubMeshes
  22970. serializationObject.subMeshes = [];
  22971. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22972. var subMesh = this.subMeshes[subIndex];
  22973. serializationObject.subMeshes.push({
  22974. materialIndex: subMesh.materialIndex,
  22975. verticesStart: subMesh.verticesStart,
  22976. verticesCount: subMesh.verticesCount,
  22977. indexStart: subMesh.indexStart,
  22978. indexCount: subMesh.indexCount
  22979. });
  22980. }
  22981. }
  22982. // Material
  22983. if (this.material) {
  22984. serializationObject.materialId = this.material.id;
  22985. }
  22986. else {
  22987. this.material = null;
  22988. }
  22989. // Morph targets
  22990. if (this.morphTargetManager) {
  22991. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22992. }
  22993. // Skeleton
  22994. if (this.skeleton) {
  22995. serializationObject.skeletonId = this.skeleton.id;
  22996. }
  22997. // Physics
  22998. //TODO implement correct serialization for physics impostors.
  22999. if (this.getPhysicsImpostor()) {
  23000. var impostor = this.getPhysicsImpostor();
  23001. serializationObject.physicsMass = impostor.getParam("mass");
  23002. serializationObject.physicsFriction = impostor.getParam("friction");
  23003. serializationObject.physicsRestitution = impostor.getParam("mass");
  23004. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23005. }
  23006. // Metadata
  23007. if (this.metadata) {
  23008. serializationObject.metadata = this.metadata;
  23009. }
  23010. // Instances
  23011. serializationObject.instances = [];
  23012. for (var index = 0; index < this.instances.length; index++) {
  23013. var instance = this.instances[index];
  23014. var serializationInstance = {
  23015. name: instance.name,
  23016. position: instance.position.asArray(),
  23017. scaling: instance.scaling.asArray()
  23018. };
  23019. if (instance.rotationQuaternion) {
  23020. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23021. }
  23022. else if (instance.rotation) {
  23023. serializationInstance.rotation = instance.rotation.asArray();
  23024. }
  23025. serializationObject.instances.push(serializationInstance);
  23026. // Animations
  23027. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23028. serializationInstance.ranges = instance.serializeAnimationRanges();
  23029. }
  23030. //
  23031. // Animations
  23032. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23033. serializationObject.ranges = this.serializeAnimationRanges();
  23034. // Layer mask
  23035. serializationObject.layerMask = this.layerMask;
  23036. // Alpha
  23037. serializationObject.alphaIndex = this.alphaIndex;
  23038. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23039. // Overlay
  23040. serializationObject.overlayAlpha = this.overlayAlpha;
  23041. serializationObject.overlayColor = this.overlayColor.asArray();
  23042. serializationObject.renderOverlay = this.renderOverlay;
  23043. // Fog
  23044. serializationObject.applyFog = this.applyFog;
  23045. // Action Manager
  23046. if (this.actionManager) {
  23047. serializationObject.actions = this.actionManager.serialize(this.name);
  23048. }
  23049. };
  23050. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23051. if (!this.geometry) {
  23052. return;
  23053. }
  23054. this._markSubMeshesAsAttributesDirty();
  23055. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23056. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23057. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23058. this.morphTargetManager = undefined;
  23059. return;
  23060. }
  23061. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23062. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23063. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23064. if (morphTarget.hasNormals) {
  23065. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23066. }
  23067. if (morphTarget.hasTangents) {
  23068. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23069. }
  23070. }
  23071. }
  23072. else {
  23073. var index = 0;
  23074. // Positions
  23075. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23076. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23077. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23078. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23079. }
  23080. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23081. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23082. }
  23083. index++;
  23084. }
  23085. }
  23086. };
  23087. // Statics
  23088. /**
  23089. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23090. * The parameter `parsedMesh` is the mesh to be copied.
  23091. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23092. */
  23093. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23094. var mesh;
  23095. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23096. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23097. }
  23098. else {
  23099. mesh = new Mesh(parsedMesh.name, scene);
  23100. }
  23101. mesh.id = parsedMesh.id;
  23102. if (BABYLON.Tags) {
  23103. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23104. }
  23105. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23106. if (parsedMesh.metadata !== undefined) {
  23107. mesh.metadata = parsedMesh.metadata;
  23108. }
  23109. if (parsedMesh.rotationQuaternion) {
  23110. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23111. }
  23112. else if (parsedMesh.rotation) {
  23113. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23114. }
  23115. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23116. if (parsedMesh.localMatrix) {
  23117. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23118. }
  23119. else if (parsedMesh.pivotMatrix) {
  23120. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23121. }
  23122. mesh.setEnabled(parsedMesh.isEnabled);
  23123. mesh.isVisible = parsedMesh.isVisible;
  23124. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23125. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23126. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23127. if (parsedMesh.applyFog !== undefined) {
  23128. mesh.applyFog = parsedMesh.applyFog;
  23129. }
  23130. if (parsedMesh.pickable !== undefined) {
  23131. mesh.isPickable = parsedMesh.pickable;
  23132. }
  23133. if (parsedMesh.alphaIndex !== undefined) {
  23134. mesh.alphaIndex = parsedMesh.alphaIndex;
  23135. }
  23136. mesh.receiveShadows = parsedMesh.receiveShadows;
  23137. mesh.billboardMode = parsedMesh.billboardMode;
  23138. if (parsedMesh.visibility !== undefined) {
  23139. mesh.visibility = parsedMesh.visibility;
  23140. }
  23141. mesh.checkCollisions = parsedMesh.checkCollisions;
  23142. if (parsedMesh.isBlocker !== undefined) {
  23143. mesh.isBlocker = parsedMesh.isBlocker;
  23144. }
  23145. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23146. // freezeWorldMatrix
  23147. if (parsedMesh.freezeWorldMatrix) {
  23148. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23149. }
  23150. // Parent
  23151. if (parsedMesh.parentId) {
  23152. mesh._waitingParentId = parsedMesh.parentId;
  23153. }
  23154. // Actions
  23155. if (parsedMesh.actions !== undefined) {
  23156. mesh._waitingActions = parsedMesh.actions;
  23157. }
  23158. // Overlay
  23159. if (parsedMesh.overlayAlpha !== undefined) {
  23160. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23161. }
  23162. if (parsedMesh.overlayColor !== undefined) {
  23163. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23164. }
  23165. if (parsedMesh.renderOverlay !== undefined) {
  23166. mesh.renderOverlay = parsedMesh.renderOverlay;
  23167. }
  23168. // Geometry
  23169. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23170. if (parsedMesh.delayLoadingFile) {
  23171. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23172. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23173. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23174. if (parsedMesh._binaryInfo) {
  23175. mesh._binaryInfo = parsedMesh._binaryInfo;
  23176. }
  23177. mesh._delayInfo = [];
  23178. if (parsedMesh.hasUVs) {
  23179. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23180. }
  23181. if (parsedMesh.hasUVs2) {
  23182. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23183. }
  23184. if (parsedMesh.hasUVs3) {
  23185. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23186. }
  23187. if (parsedMesh.hasUVs4) {
  23188. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23189. }
  23190. if (parsedMesh.hasUVs5) {
  23191. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23192. }
  23193. if (parsedMesh.hasUVs6) {
  23194. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23195. }
  23196. if (parsedMesh.hasColors) {
  23197. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23198. }
  23199. if (parsedMesh.hasMatricesIndices) {
  23200. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23201. }
  23202. if (parsedMesh.hasMatricesWeights) {
  23203. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23204. }
  23205. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23206. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23207. mesh._checkDelayState();
  23208. }
  23209. }
  23210. else {
  23211. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23212. }
  23213. // Material
  23214. if (parsedMesh.materialId) {
  23215. mesh.setMaterialByID(parsedMesh.materialId);
  23216. }
  23217. else {
  23218. mesh.material = null;
  23219. }
  23220. // Morph targets
  23221. if (parsedMesh.morphTargetManagerId > -1) {
  23222. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23223. }
  23224. // Skeleton
  23225. if (parsedMesh.skeletonId > -1) {
  23226. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23227. if (parsedMesh.numBoneInfluencers) {
  23228. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23229. }
  23230. }
  23231. // Animations
  23232. if (parsedMesh.animations) {
  23233. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23234. var parsedAnimation = parsedMesh.animations[animationIndex];
  23235. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23236. }
  23237. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23238. }
  23239. if (parsedMesh.autoAnimate) {
  23240. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23241. }
  23242. // Layer Mask
  23243. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23244. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23245. }
  23246. else {
  23247. mesh.layerMask = 0x0FFFFFFF;
  23248. }
  23249. // Physics
  23250. if (parsedMesh.physicsImpostor) {
  23251. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23252. mass: parsedMesh.physicsMass,
  23253. friction: parsedMesh.physicsFriction,
  23254. restitution: parsedMesh.physicsRestitution
  23255. }, scene);
  23256. }
  23257. // Instances
  23258. if (parsedMesh.instances) {
  23259. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23260. var parsedInstance = parsedMesh.instances[index];
  23261. var instance = mesh.createInstance(parsedInstance.name);
  23262. if (BABYLON.Tags) {
  23263. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23264. }
  23265. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23266. if (parsedInstance.parentId) {
  23267. instance._waitingParentId = parsedInstance.parentId;
  23268. }
  23269. if (parsedInstance.rotationQuaternion) {
  23270. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23271. }
  23272. else if (parsedInstance.rotation) {
  23273. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23274. }
  23275. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23276. instance.checkCollisions = mesh.checkCollisions;
  23277. if (parsedMesh.animations) {
  23278. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23279. parsedAnimation = parsedMesh.animations[animationIndex];
  23280. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23281. }
  23282. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23283. }
  23284. }
  23285. }
  23286. return mesh;
  23287. };
  23288. /**
  23289. * Creates a ribbon mesh.
  23290. * Please consider using the same method from the MeshBuilder class instead.
  23291. * 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.
  23292. *
  23293. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23294. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23295. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23296. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23297. * 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.
  23298. * 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.
  23299. * 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
  23300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23303. */
  23304. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23305. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23306. pathArray: pathArray,
  23307. closeArray: closeArray,
  23308. closePath: closePath,
  23309. offset: offset,
  23310. updatable: updatable,
  23311. sideOrientation: sideOrientation,
  23312. instance: instance
  23313. }, scene);
  23314. };
  23315. /**
  23316. * Creates a plane polygonal mesh. By default, this is a disc.
  23317. * Please consider using the same method from the MeshBuilder class instead.
  23318. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23319. * 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.
  23320. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23323. */
  23324. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23325. var options = {
  23326. radius: radius,
  23327. tessellation: tessellation,
  23328. sideOrientation: sideOrientation,
  23329. updatable: updatable
  23330. };
  23331. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23332. };
  23333. /**
  23334. * Creates a box mesh.
  23335. * Please consider using the same method from the MeshBuilder class instead.
  23336. * The parameter `size` sets the size (float) of each box side (default 1).
  23337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23340. */
  23341. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23342. var options = {
  23343. size: size,
  23344. sideOrientation: sideOrientation,
  23345. updatable: updatable
  23346. };
  23347. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23348. };
  23349. /**
  23350. * Creates a sphere mesh.
  23351. * Please consider using the same method from the MeshBuilder class instead.
  23352. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23353. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23357. */
  23358. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23359. var options = {
  23360. segments: segments,
  23361. diameterX: diameter,
  23362. diameterY: diameter,
  23363. diameterZ: diameter,
  23364. sideOrientation: sideOrientation,
  23365. updatable: updatable
  23366. };
  23367. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23368. };
  23369. /**
  23370. * Creates a cylinder or a cone mesh.
  23371. * Please consider using the same method from the MeshBuilder class instead.
  23372. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23373. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23374. * 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.
  23375. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23376. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23380. */
  23381. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23382. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23383. if (scene !== undefined) {
  23384. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23385. updatable = scene;
  23386. }
  23387. scene = subdivisions;
  23388. subdivisions = 1;
  23389. }
  23390. var options = {
  23391. height: height,
  23392. diameterTop: diameterTop,
  23393. diameterBottom: diameterBottom,
  23394. tessellation: tessellation,
  23395. subdivisions: subdivisions,
  23396. sideOrientation: sideOrientation,
  23397. updatable: updatable
  23398. };
  23399. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23400. };
  23401. // Torus (Code from SharpDX.org)
  23402. /**
  23403. * Creates a torus mesh.
  23404. * Please consider using the same method from the MeshBuilder class instead.
  23405. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23406. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23407. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23411. */
  23412. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23413. var options = {
  23414. diameter: diameter,
  23415. thickness: thickness,
  23416. tessellation: tessellation,
  23417. sideOrientation: sideOrientation,
  23418. updatable: updatable
  23419. };
  23420. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23421. };
  23422. /**
  23423. * Creates a torus knot mesh.
  23424. * Please consider using the same method from the MeshBuilder class instead.
  23425. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23426. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23427. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23428. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23432. */
  23433. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23434. var options = {
  23435. radius: radius,
  23436. tube: tube,
  23437. radialSegments: radialSegments,
  23438. tubularSegments: tubularSegments,
  23439. p: p,
  23440. q: q,
  23441. sideOrientation: sideOrientation,
  23442. updatable: updatable
  23443. };
  23444. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23445. };
  23446. /**
  23447. * Creates a line mesh.
  23448. * Please consider using the same method from the MeshBuilder class instead.
  23449. * 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.
  23450. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23451. * The parameter `points` is an array successive Vector3.
  23452. * 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
  23453. * When updating an instance, remember that only point positions can change, not the number of points.
  23454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23455. */
  23456. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23457. var options = {
  23458. points: points,
  23459. updatable: updatable,
  23460. instance: instance
  23461. };
  23462. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23463. };
  23464. /**
  23465. * Creates a dashed line mesh.
  23466. * Please consider using the same method from the MeshBuilder class instead.
  23467. * 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.
  23468. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23469. * The parameter `points` is an array successive Vector3.
  23470. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23471. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23472. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23473. * 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
  23474. * When updating an instance, remember that only point positions can change, not the number of points.
  23475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23476. */
  23477. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23478. var options = {
  23479. points: points,
  23480. dashSize: dashSize,
  23481. gapSize: gapSize,
  23482. dashNb: dashNb,
  23483. updatable: updatable,
  23484. instance: instance
  23485. };
  23486. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23487. };
  23488. /**
  23489. * Creates a polygon mesh.
  23490. * Please consider using the same method from the MeshBuilder class instead.
  23491. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23492. * 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.
  23493. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23495. * Remember you can only change the shape positions, not their number when updating a polygon.
  23496. */
  23497. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23498. var options = {
  23499. shape: shape,
  23500. holes: holes,
  23501. updatable: updatable,
  23502. sideOrientation: sideOrientation
  23503. };
  23504. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23505. };
  23506. /**
  23507. * Creates an extruded polygon mesh, with depth in the Y direction.
  23508. * Please consider using the same method from the MeshBuilder class instead.
  23509. */
  23510. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23511. var options = {
  23512. shape: shape,
  23513. holes: holes,
  23514. depth: depth,
  23515. updatable: updatable,
  23516. sideOrientation: sideOrientation
  23517. };
  23518. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23519. };
  23520. /**
  23521. * Creates an extruded shape mesh.
  23522. * 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.
  23523. * Please consider using the same method from the MeshBuilder class instead.
  23524. *
  23525. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23526. * 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
  23527. * extruded along the Z axis.
  23528. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23529. * 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.
  23530. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23531. * 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
  23532. * 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
  23533. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23537. */
  23538. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23539. var options = {
  23540. shape: shape,
  23541. path: path,
  23542. scale: scale,
  23543. rotation: rotation,
  23544. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23545. sideOrientation: sideOrientation,
  23546. instance: instance,
  23547. updatable: updatable
  23548. };
  23549. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23550. };
  23551. /**
  23552. * Creates an custom extruded shape mesh.
  23553. * 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.
  23554. * Please consider using the same method from the MeshBuilder class instead.
  23555. *
  23556. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23557. * 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
  23558. * extruded along the Z axis.
  23559. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23560. * 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
  23561. * and the distance of this point from the begining of the path :
  23562. * ```javascript
  23563. * var rotationFunction = function(i, distance) {
  23564. * // do things
  23565. * return rotationValue; }
  23566. * ```
  23567. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23568. * 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
  23569. * and the distance of this point from the begining of the path :
  23570. * ```javascript
  23571. * var scaleFunction = function(i, distance) {
  23572. * // do things
  23573. * return scaleValue;}
  23574. * ```
  23575. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23576. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23577. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23578. * 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
  23579. * 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
  23580. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23581. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23582. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23584. */
  23585. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23586. var options = {
  23587. shape: shape,
  23588. path: path,
  23589. scaleFunction: scaleFunction,
  23590. rotationFunction: rotationFunction,
  23591. ribbonCloseArray: ribbonCloseArray,
  23592. ribbonClosePath: ribbonClosePath,
  23593. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23594. sideOrientation: sideOrientation,
  23595. instance: instance,
  23596. updatable: updatable
  23597. };
  23598. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23599. };
  23600. /**
  23601. * Creates lathe mesh.
  23602. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23603. * Please consider using the same method from the MeshBuilder class instead.
  23604. * 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
  23605. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23606. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23607. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23611. */
  23612. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23613. var options = {
  23614. shape: shape,
  23615. radius: radius,
  23616. tessellation: tessellation,
  23617. sideOrientation: sideOrientation,
  23618. updatable: updatable
  23619. };
  23620. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23621. };
  23622. /**
  23623. * Creates a plane mesh.
  23624. * Please consider using the same method from the MeshBuilder class instead.
  23625. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23629. */
  23630. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23631. var options = {
  23632. size: size,
  23633. width: size,
  23634. height: size,
  23635. sideOrientation: sideOrientation,
  23636. updatable: updatable
  23637. };
  23638. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23639. };
  23640. /**
  23641. * Creates a ground mesh.
  23642. * Please consider using the same method from the MeshBuilder class instead.
  23643. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23644. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  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.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23648. var options = {
  23649. width: width,
  23650. height: height,
  23651. subdivisions: subdivisions,
  23652. updatable: updatable
  23653. };
  23654. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23655. };
  23656. /**
  23657. * Creates a tiled ground mesh.
  23658. * Please consider using the same method from the MeshBuilder class instead.
  23659. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23660. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23661. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23662. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23663. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23664. * numbers of subdivisions on the ground width and height of each tile.
  23665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23666. */
  23667. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23668. var options = {
  23669. xmin: xmin,
  23670. zmin: zmin,
  23671. xmax: xmax,
  23672. zmax: zmax,
  23673. subdivisions: subdivisions,
  23674. precision: precision,
  23675. updatable: updatable
  23676. };
  23677. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23678. };
  23679. /**
  23680. * Creates a ground mesh from a height map.
  23681. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23682. * Please consider using the same method from the MeshBuilder class instead.
  23683. * The parameter `url` sets the URL of the height map image resource.
  23684. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23685. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23686. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23687. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23688. * 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).
  23689. * This function is passed the newly built mesh :
  23690. * ```javascript
  23691. * function(mesh) { // do things
  23692. * return; }
  23693. * ```
  23694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23695. */
  23696. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23697. var options = {
  23698. width: width,
  23699. height: height,
  23700. subdivisions: subdivisions,
  23701. minHeight: minHeight,
  23702. maxHeight: maxHeight,
  23703. updatable: updatable,
  23704. onReady: onReady
  23705. };
  23706. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23707. };
  23708. /**
  23709. * Creates a tube mesh.
  23710. * 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.
  23711. * Please consider using the same method from the MeshBuilder class instead.
  23712. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23713. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23714. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23715. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23716. * 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.
  23717. * It must return a radius value (positive float) :
  23718. * ```javascript
  23719. * var radiusFunction = function(i, distance) {
  23720. * // do things
  23721. * return radius; }
  23722. * ```
  23723. * 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
  23724. * 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
  23725. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23726. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23728. */
  23729. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23730. var options = {
  23731. path: path,
  23732. radius: radius,
  23733. tessellation: tessellation,
  23734. radiusFunction: radiusFunction,
  23735. arc: 1,
  23736. cap: cap,
  23737. updatable: updatable,
  23738. sideOrientation: sideOrientation,
  23739. instance: instance
  23740. };
  23741. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23742. };
  23743. /**
  23744. * Creates a polyhedron mesh.
  23745. * Please consider using the same method from the MeshBuilder class instead.
  23746. * 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
  23747. * to choose the wanted type.
  23748. * The parameter `size` (positive float, default 1) sets the polygon size.
  23749. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23750. * 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`.
  23751. * 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
  23752. * 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)`).
  23753. * 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
  23754. * 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.
  23755. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23758. */
  23759. Mesh.CreatePolyhedron = function (name, options, scene) {
  23760. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23761. };
  23762. /**
  23763. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23764. * Please consider using the same method from the MeshBuilder class instead.
  23765. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23766. * 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`).
  23767. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23768. * 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.
  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.CreateIcoSphere = function (name, options, scene) {
  23774. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23775. };
  23776. /**
  23777. * Creates a decal mesh.
  23778. * Please consider using the same method from the MeshBuilder class instead.
  23779. * 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.
  23780. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23781. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23782. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23783. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23784. */
  23785. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23786. var options = {
  23787. position: position,
  23788. normal: normal,
  23789. size: size,
  23790. angle: angle
  23791. };
  23792. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23793. };
  23794. // Skeletons
  23795. /**
  23796. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23797. */
  23798. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23799. var source;
  23800. if (!this._sourcePositions) {
  23801. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23802. this._sourcePositions = new Float32Array(source);
  23803. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23804. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23805. }
  23806. }
  23807. return this._sourcePositions;
  23808. };
  23809. /**
  23810. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23811. */
  23812. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23813. var source;
  23814. if (!this._sourceNormals) {
  23815. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23816. this._sourceNormals = new Float32Array(source);
  23817. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23818. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23819. }
  23820. }
  23821. return this._sourceNormals;
  23822. };
  23823. /**
  23824. * Updates the vertex buffer by applying transformation from the bones.
  23825. * Returns the Mesh.
  23826. *
  23827. * @param {skeleton} skeleton to apply
  23828. */
  23829. Mesh.prototype.applySkeleton = function (skeleton) {
  23830. if (!this.geometry) {
  23831. return this;
  23832. }
  23833. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23834. return this;
  23835. }
  23836. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23837. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23838. return this;
  23839. }
  23840. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23841. return this;
  23842. }
  23843. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23844. return this;
  23845. }
  23846. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23847. return this;
  23848. }
  23849. if (!this._sourcePositions) {
  23850. var submeshes = this.subMeshes.slice();
  23851. this.setPositionsForCPUSkinning();
  23852. this.subMeshes = submeshes;
  23853. }
  23854. if (!this._sourceNormals) {
  23855. this.setNormalsForCPUSkinning();
  23856. }
  23857. // positionsData checks for not being Float32Array will only pass at most once
  23858. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23859. if (!(positionsData instanceof Float32Array)) {
  23860. positionsData = new Float32Array(positionsData);
  23861. }
  23862. // normalsData checks for not being Float32Array will only pass at most once
  23863. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23864. if (!(normalsData instanceof Float32Array)) {
  23865. normalsData = new Float32Array(normalsData);
  23866. }
  23867. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23868. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23869. var needExtras = this.numBoneInfluencers > 4;
  23870. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23871. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23872. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23873. var tempVector3 = BABYLON.Vector3.Zero();
  23874. var finalMatrix = new BABYLON.Matrix();
  23875. var tempMatrix = new BABYLON.Matrix();
  23876. var matWeightIdx = 0;
  23877. var inf;
  23878. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23879. var weight;
  23880. for (inf = 0; inf < 4; inf++) {
  23881. weight = matricesWeightsData[matWeightIdx + inf];
  23882. if (weight > 0) {
  23883. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23884. finalMatrix.addToSelf(tempMatrix);
  23885. }
  23886. else
  23887. break;
  23888. }
  23889. if (needExtras) {
  23890. for (inf = 0; inf < 4; inf++) {
  23891. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23892. if (weight > 0) {
  23893. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23894. finalMatrix.addToSelf(tempMatrix);
  23895. }
  23896. else
  23897. break;
  23898. }
  23899. }
  23900. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23901. tempVector3.toArray(positionsData, index);
  23902. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23903. tempVector3.toArray(normalsData, index);
  23904. finalMatrix.reset();
  23905. }
  23906. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23907. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23908. return this;
  23909. };
  23910. // Tools
  23911. /**
  23912. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23913. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23914. */
  23915. Mesh.MinMax = function (meshes) {
  23916. var minVector = null;
  23917. var maxVector = null;
  23918. meshes.forEach(function (mesh, index, array) {
  23919. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23920. if (!minVector) {
  23921. minVector = boundingBox.minimumWorld;
  23922. maxVector = boundingBox.maximumWorld;
  23923. }
  23924. else {
  23925. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23926. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23927. }
  23928. });
  23929. return {
  23930. min: minVector,
  23931. max: maxVector
  23932. };
  23933. };
  23934. /**
  23935. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23936. */
  23937. Mesh.Center = function (meshesOrMinMaxVector) {
  23938. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23939. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23940. };
  23941. /**
  23942. * Merge the array of meshes into a single mesh for performance reasons.
  23943. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23944. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23945. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23946. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23947. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23948. */
  23949. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23950. if (disposeSource === void 0) { disposeSource = true; }
  23951. var index;
  23952. if (!allow32BitsIndices) {
  23953. var totalVertices = 0;
  23954. // Counting vertices
  23955. for (index = 0; index < meshes.length; index++) {
  23956. if (meshes[index]) {
  23957. totalVertices += meshes[index].getTotalVertices();
  23958. if (totalVertices > 65536) {
  23959. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23960. return null;
  23961. }
  23962. }
  23963. }
  23964. }
  23965. // Merge
  23966. var vertexData;
  23967. var otherVertexData;
  23968. var indiceArray = new Array();
  23969. var source;
  23970. for (index = 0; index < meshes.length; index++) {
  23971. if (meshes[index]) {
  23972. meshes[index].computeWorldMatrix(true);
  23973. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23974. otherVertexData.transform(meshes[index].getWorldMatrix());
  23975. if (vertexData) {
  23976. vertexData.merge(otherVertexData);
  23977. }
  23978. else {
  23979. vertexData = otherVertexData;
  23980. source = meshes[index];
  23981. }
  23982. if (subdivideWithSubMeshes) {
  23983. indiceArray.push(meshes[index].getTotalIndices());
  23984. }
  23985. }
  23986. }
  23987. if (!meshSubclass) {
  23988. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23989. }
  23990. vertexData.applyToMesh(meshSubclass);
  23991. // Setting properties
  23992. meshSubclass.material = source.material;
  23993. meshSubclass.checkCollisions = source.checkCollisions;
  23994. // Cleaning
  23995. if (disposeSource) {
  23996. for (index = 0; index < meshes.length; index++) {
  23997. if (meshes[index]) {
  23998. meshes[index].dispose();
  23999. }
  24000. }
  24001. }
  24002. // Subdivide
  24003. if (subdivideWithSubMeshes) {
  24004. //-- Suppresions du submesh global
  24005. meshSubclass.releaseSubMeshes();
  24006. index = 0;
  24007. var offset = 0;
  24008. //-- aplique la subdivision en fonction du tableau d'indices
  24009. while (index < indiceArray.length) {
  24010. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24011. offset += indiceArray[index];
  24012. index++;
  24013. }
  24014. }
  24015. return meshSubclass;
  24016. };
  24017. // Consts
  24018. Mesh._FRONTSIDE = 0;
  24019. Mesh._BACKSIDE = 1;
  24020. Mesh._DOUBLESIDE = 2;
  24021. Mesh._DEFAULTSIDE = 0;
  24022. Mesh._NO_CAP = 0;
  24023. Mesh._CAP_START = 1;
  24024. Mesh._CAP_END = 2;
  24025. Mesh._CAP_ALL = 3;
  24026. return Mesh;
  24027. }(BABYLON.AbstractMesh));
  24028. BABYLON.Mesh = Mesh;
  24029. })(BABYLON || (BABYLON = {}));
  24030. //# sourceMappingURL=babylon.mesh.js.map
  24031. var BABYLON;
  24032. (function (BABYLON) {
  24033. var BaseSubMesh = (function () {
  24034. function BaseSubMesh() {
  24035. }
  24036. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24037. get: function () {
  24038. return this._materialEffect;
  24039. },
  24040. enumerable: true,
  24041. configurable: true
  24042. });
  24043. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24044. if (this._materialEffect === effect) {
  24045. if (!effect) {
  24046. this._materialDefines = undefined;
  24047. }
  24048. return;
  24049. }
  24050. this._materialDefines = defines;
  24051. this._materialEffect = effect;
  24052. };
  24053. return BaseSubMesh;
  24054. }());
  24055. BABYLON.BaseSubMesh = BaseSubMesh;
  24056. var SubMesh = (function (_super) {
  24057. __extends(SubMesh, _super);
  24058. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24059. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24060. var _this = _super.call(this) || this;
  24061. _this.materialIndex = materialIndex;
  24062. _this.verticesStart = verticesStart;
  24063. _this.verticesCount = verticesCount;
  24064. _this.indexStart = indexStart;
  24065. _this.indexCount = indexCount;
  24066. _this._renderId = 0;
  24067. _this._mesh = mesh;
  24068. _this._renderingMesh = renderingMesh || mesh;
  24069. mesh.subMeshes.push(_this);
  24070. _this._trianglePlanes = [];
  24071. _this._id = mesh.subMeshes.length - 1;
  24072. if (createBoundingBox) {
  24073. _this.refreshBoundingInfo();
  24074. mesh.computeWorldMatrix(true);
  24075. }
  24076. return _this;
  24077. }
  24078. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24079. get: function () {
  24080. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24081. },
  24082. enumerable: true,
  24083. configurable: true
  24084. });
  24085. /**
  24086. * Returns the submesh BoudingInfo object.
  24087. */
  24088. SubMesh.prototype.getBoundingInfo = function () {
  24089. if (this.IsGlobal) {
  24090. return this._mesh.getBoundingInfo();
  24091. }
  24092. return this._boundingInfo;
  24093. };
  24094. /**
  24095. * Sets the submesh BoundingInfo.
  24096. * Return the SubMesh.
  24097. */
  24098. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24099. this._boundingInfo = boundingInfo;
  24100. return this;
  24101. };
  24102. /**
  24103. * Returns the mesh of the current submesh.
  24104. */
  24105. SubMesh.prototype.getMesh = function () {
  24106. return this._mesh;
  24107. };
  24108. /**
  24109. * Returns the rendering mesh of the submesh.
  24110. */
  24111. SubMesh.prototype.getRenderingMesh = function () {
  24112. return this._renderingMesh;
  24113. };
  24114. /**
  24115. * Returns the submesh material.
  24116. */
  24117. SubMesh.prototype.getMaterial = function () {
  24118. var rootMaterial = this._renderingMesh.material;
  24119. if (rootMaterial && rootMaterial.getSubMaterial) {
  24120. var multiMaterial = rootMaterial;
  24121. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24122. if (this._currentMaterial !== effectiveMaterial) {
  24123. this._currentMaterial = effectiveMaterial;
  24124. this._materialDefines = undefined;
  24125. }
  24126. return effectiveMaterial;
  24127. }
  24128. if (!rootMaterial) {
  24129. return this._mesh.getScene().defaultMaterial;
  24130. }
  24131. return rootMaterial;
  24132. };
  24133. // Methods
  24134. /**
  24135. * Sets a new updated BoundingInfo object to the submesh.
  24136. * Returns the SubMesh.
  24137. */
  24138. SubMesh.prototype.refreshBoundingInfo = function () {
  24139. this._lastColliderWorldVertices = null;
  24140. if (this.IsGlobal) {
  24141. return;
  24142. }
  24143. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24144. if (!data) {
  24145. this._boundingInfo = this._mesh._boundingInfo;
  24146. return;
  24147. }
  24148. var indices = this._renderingMesh.getIndices();
  24149. var extend;
  24150. //is this the only submesh?
  24151. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24152. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24153. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24154. }
  24155. else {
  24156. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24157. }
  24158. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24159. return this;
  24160. };
  24161. SubMesh.prototype._checkCollision = function (collider) {
  24162. return this.getBoundingInfo()._checkCollision(collider);
  24163. };
  24164. /**
  24165. * Updates the submesh BoundingInfo.
  24166. * Returns the Submesh.
  24167. */
  24168. SubMesh.prototype.updateBoundingInfo = function (world) {
  24169. if (!this.getBoundingInfo()) {
  24170. this.refreshBoundingInfo();
  24171. }
  24172. this.getBoundingInfo().update(world);
  24173. return this;
  24174. };
  24175. /**
  24176. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24177. * Boolean returned.
  24178. */
  24179. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24180. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24181. };
  24182. /**
  24183. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24184. * Boolean returned.
  24185. */
  24186. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24187. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24188. };
  24189. /**
  24190. * Renders the submesh.
  24191. * Returns it.
  24192. */
  24193. SubMesh.prototype.render = function (enableAlphaMode) {
  24194. this._renderingMesh.render(this, enableAlphaMode);
  24195. return this;
  24196. };
  24197. /**
  24198. * Returns a new Index Buffer.
  24199. * Type returned : WebGLBuffer.
  24200. */
  24201. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24202. if (!this._linesIndexBuffer) {
  24203. var linesIndices = [];
  24204. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24205. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24206. }
  24207. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24208. this.linesIndexCount = linesIndices.length;
  24209. }
  24210. return this._linesIndexBuffer;
  24211. };
  24212. /**
  24213. * True is the passed Ray intersects the submesh bounding box.
  24214. * Boolean returned.
  24215. */
  24216. SubMesh.prototype.canIntersects = function (ray) {
  24217. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24218. };
  24219. /**
  24220. * Returns an object IntersectionInfo.
  24221. */
  24222. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24223. var intersectInfo = null;
  24224. // LineMesh first as it's also a Mesh...
  24225. if (this._mesh instanceof BABYLON.LinesMesh) {
  24226. var lineMesh = this._mesh;
  24227. // Line test
  24228. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24229. var p0 = positions[indices[index]];
  24230. var p1 = positions[indices[index + 1]];
  24231. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24232. if (length < 0) {
  24233. continue;
  24234. }
  24235. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24236. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24237. if (fastCheck) {
  24238. break;
  24239. }
  24240. }
  24241. }
  24242. }
  24243. else {
  24244. // Triangles test
  24245. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24246. var p0 = positions[indices[index]];
  24247. var p1 = positions[indices[index + 1]];
  24248. var p2 = positions[indices[index + 2]];
  24249. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24250. if (currentIntersectInfo) {
  24251. if (currentIntersectInfo.distance < 0) {
  24252. continue;
  24253. }
  24254. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24255. intersectInfo = currentIntersectInfo;
  24256. intersectInfo.faceId = index / 3;
  24257. if (fastCheck) {
  24258. break;
  24259. }
  24260. }
  24261. }
  24262. }
  24263. }
  24264. return intersectInfo;
  24265. };
  24266. SubMesh.prototype._rebuild = function () {
  24267. if (this._linesIndexBuffer) {
  24268. this._linesIndexBuffer = null;
  24269. }
  24270. };
  24271. // Clone
  24272. /**
  24273. * Creates a new Submesh from the passed Mesh.
  24274. */
  24275. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24276. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24277. if (!this.IsGlobal) {
  24278. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24279. }
  24280. return result;
  24281. };
  24282. // Dispose
  24283. /**
  24284. * Disposes the Submesh.
  24285. * Returns nothing.
  24286. */
  24287. SubMesh.prototype.dispose = function () {
  24288. if (this._linesIndexBuffer) {
  24289. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24290. this._linesIndexBuffer = null;
  24291. }
  24292. // Remove from mesh
  24293. var index = this._mesh.subMeshes.indexOf(this);
  24294. this._mesh.subMeshes.splice(index, 1);
  24295. };
  24296. // Statics
  24297. /**
  24298. * Creates a new Submesh from the passed parameters :
  24299. * - materialIndex (integer) : the index of the main mesh material.
  24300. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24301. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24302. * - mesh (Mesh) : the main mesh to create the submesh from.
  24303. * - renderingMesh (optional Mesh) : rendering mesh.
  24304. */
  24305. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24306. var minVertexIndex = Number.MAX_VALUE;
  24307. var maxVertexIndex = -Number.MAX_VALUE;
  24308. renderingMesh = renderingMesh || mesh;
  24309. var indices = renderingMesh.getIndices();
  24310. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24311. var vertexIndex = indices[index];
  24312. if (vertexIndex < minVertexIndex)
  24313. minVertexIndex = vertexIndex;
  24314. if (vertexIndex > maxVertexIndex)
  24315. maxVertexIndex = vertexIndex;
  24316. }
  24317. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24318. };
  24319. return SubMesh;
  24320. }(BaseSubMesh));
  24321. BABYLON.SubMesh = SubMesh;
  24322. })(BABYLON || (BABYLON = {}));
  24323. //# sourceMappingURL=babylon.subMesh.js.map
  24324. var BABYLON;
  24325. (function (BABYLON) {
  24326. var EffectFallbacks = (function () {
  24327. function EffectFallbacks() {
  24328. this._defines = {};
  24329. this._currentRank = 32;
  24330. this._maxRank = -1;
  24331. }
  24332. EffectFallbacks.prototype.unBindMesh = function () {
  24333. this._mesh = null;
  24334. };
  24335. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24336. if (!this._defines[rank]) {
  24337. if (rank < this._currentRank) {
  24338. this._currentRank = rank;
  24339. }
  24340. if (rank > this._maxRank) {
  24341. this._maxRank = rank;
  24342. }
  24343. this._defines[rank] = new Array();
  24344. }
  24345. this._defines[rank].push(define);
  24346. };
  24347. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24348. this._meshRank = rank;
  24349. this._mesh = mesh;
  24350. if (rank < this._currentRank) {
  24351. this._currentRank = rank;
  24352. }
  24353. if (rank > this._maxRank) {
  24354. this._maxRank = rank;
  24355. }
  24356. };
  24357. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24358. get: function () {
  24359. return this._currentRank <= this._maxRank;
  24360. },
  24361. enumerable: true,
  24362. configurable: true
  24363. });
  24364. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24365. // First we try to switch to CPU skinning
  24366. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24367. this._mesh.computeBonesUsingShaders = false;
  24368. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24369. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24370. var scene = this._mesh.getScene();
  24371. for (var index = 0; index < scene.meshes.length; index++) {
  24372. var otherMesh = scene.meshes[index];
  24373. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24374. otherMesh.computeBonesUsingShaders = false;
  24375. }
  24376. }
  24377. }
  24378. else {
  24379. var currentFallbacks = this._defines[this._currentRank];
  24380. if (currentFallbacks) {
  24381. for (var index = 0; index < currentFallbacks.length; index++) {
  24382. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24383. }
  24384. }
  24385. this._currentRank++;
  24386. }
  24387. return currentDefines;
  24388. };
  24389. return EffectFallbacks;
  24390. }());
  24391. BABYLON.EffectFallbacks = EffectFallbacks;
  24392. var EffectCreationOptions = (function () {
  24393. function EffectCreationOptions() {
  24394. }
  24395. return EffectCreationOptions;
  24396. }());
  24397. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24398. var Effect = (function () {
  24399. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24400. var _this = this;
  24401. this.uniqueId = 0;
  24402. this.onCompileObservable = new BABYLON.Observable();
  24403. this.onErrorObservable = new BABYLON.Observable();
  24404. this.onBindObservable = new BABYLON.Observable();
  24405. this._uniformBuffersNames = {};
  24406. this._isReady = false;
  24407. this._compilationError = "";
  24408. this.name = baseName;
  24409. if (attributesNamesOrOptions.attributes) {
  24410. var options = attributesNamesOrOptions;
  24411. this._engine = uniformsNamesOrEngine;
  24412. this._attributesNames = options.attributes;
  24413. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24414. this._samplers = options.samplers;
  24415. this.defines = options.defines;
  24416. this.onError = options.onError;
  24417. this.onCompiled = options.onCompiled;
  24418. this._fallbacks = options.fallbacks;
  24419. this._indexParameters = options.indexParameters;
  24420. if (options.uniformBuffersNames) {
  24421. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24422. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24423. }
  24424. }
  24425. }
  24426. else {
  24427. this._engine = engine;
  24428. this.defines = defines;
  24429. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24430. this._samplers = samplers;
  24431. this._attributesNames = attributesNamesOrOptions;
  24432. this.onError = onError;
  24433. this.onCompiled = onCompiled;
  24434. this._indexParameters = indexParameters;
  24435. this._fallbacks = fallbacks;
  24436. }
  24437. this.uniqueId = Effect._uniqueIdSeed++;
  24438. var vertexSource;
  24439. var fragmentSource;
  24440. if (baseName.vertexElement) {
  24441. vertexSource = document.getElementById(baseName.vertexElement);
  24442. if (!vertexSource) {
  24443. vertexSource = baseName.vertexElement;
  24444. }
  24445. }
  24446. else {
  24447. vertexSource = baseName.vertex || baseName;
  24448. }
  24449. if (baseName.fragmentElement) {
  24450. fragmentSource = document.getElementById(baseName.fragmentElement);
  24451. if (!fragmentSource) {
  24452. fragmentSource = baseName.fragmentElement;
  24453. }
  24454. }
  24455. else {
  24456. fragmentSource = baseName.fragment || baseName;
  24457. }
  24458. this._loadVertexShader(vertexSource, function (vertexCode) {
  24459. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24460. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24461. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24462. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24463. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24464. if (baseName) {
  24465. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24466. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24467. }
  24468. else {
  24469. _this._vertexSourceCode = migratedVertexCode;
  24470. _this._fragmentSourceCode = migratedFragmentCode;
  24471. }
  24472. _this._prepareEffect();
  24473. });
  24474. });
  24475. });
  24476. });
  24477. });
  24478. });
  24479. }
  24480. Object.defineProperty(Effect.prototype, "key", {
  24481. get: function () {
  24482. return this._key;
  24483. },
  24484. enumerable: true,
  24485. configurable: true
  24486. });
  24487. // Properties
  24488. Effect.prototype.isReady = function () {
  24489. return this._isReady;
  24490. };
  24491. Effect.prototype.getEngine = function () {
  24492. return this._engine;
  24493. };
  24494. Effect.prototype.getProgram = function () {
  24495. return this._program;
  24496. };
  24497. Effect.prototype.getAttributesNames = function () {
  24498. return this._attributesNames;
  24499. };
  24500. Effect.prototype.getAttributeLocation = function (index) {
  24501. return this._attributes[index];
  24502. };
  24503. Effect.prototype.getAttributeLocationByName = function (name) {
  24504. var index = this._attributesNames.indexOf(name);
  24505. return this._attributes[index];
  24506. };
  24507. Effect.prototype.getAttributesCount = function () {
  24508. return this._attributes.length;
  24509. };
  24510. Effect.prototype.getUniformIndex = function (uniformName) {
  24511. return this._uniformsNames.indexOf(uniformName);
  24512. };
  24513. Effect.prototype.getUniform = function (uniformName) {
  24514. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24515. };
  24516. Effect.prototype.getSamplers = function () {
  24517. return this._samplers;
  24518. };
  24519. Effect.prototype.getCompilationError = function () {
  24520. return this._compilationError;
  24521. };
  24522. // Methods
  24523. Effect.prototype.executeWhenCompiled = function (func) {
  24524. if (this.isReady()) {
  24525. func(this);
  24526. return;
  24527. }
  24528. this.onCompileObservable.add(function (effect) {
  24529. func(effect);
  24530. });
  24531. };
  24532. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24533. // DOM element ?
  24534. if (vertex instanceof HTMLElement) {
  24535. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24536. callback(vertexCode);
  24537. return;
  24538. }
  24539. // Base64 encoded ?
  24540. if (vertex.substr(0, 7) === "base64:") {
  24541. var vertexBinary = window.atob(vertex.substr(7));
  24542. callback(vertexBinary);
  24543. return;
  24544. }
  24545. // Is in local store ?
  24546. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24547. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24548. return;
  24549. }
  24550. var vertexShaderUrl;
  24551. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24552. vertexShaderUrl = vertex;
  24553. }
  24554. else {
  24555. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24556. }
  24557. // Vertex shader
  24558. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24559. };
  24560. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24561. // DOM element ?
  24562. if (fragment instanceof HTMLElement) {
  24563. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24564. callback(fragmentCode);
  24565. return;
  24566. }
  24567. // Base64 encoded ?
  24568. if (fragment.substr(0, 7) === "base64:") {
  24569. var fragmentBinary = window.atob(fragment.substr(7));
  24570. callback(fragmentBinary);
  24571. return;
  24572. }
  24573. // Is in local store ?
  24574. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24575. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24576. return;
  24577. }
  24578. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24579. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24580. return;
  24581. }
  24582. var fragmentShaderUrl;
  24583. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24584. fragmentShaderUrl = fragment;
  24585. }
  24586. else {
  24587. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24588. }
  24589. // Fragment shader
  24590. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24591. };
  24592. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24593. // Rebuild shaders source code
  24594. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24595. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24596. vertexCode = prefix + vertexCode;
  24597. fragmentCode = prefix + fragmentCode;
  24598. // Number lines of shaders source code
  24599. var i = 2;
  24600. var regex = /\n/gm;
  24601. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24602. i = 2;
  24603. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24604. // Dump shaders name and formatted source code
  24605. if (this.name.vertexElement) {
  24606. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24607. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24608. }
  24609. else if (this.name.vertex) {
  24610. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24611. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24612. }
  24613. else {
  24614. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24615. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24616. }
  24617. };
  24618. ;
  24619. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24620. var preparedSourceCode = this._processPrecision(sourceCode);
  24621. if (this._engine.webGLVersion == 1) {
  24622. callback(preparedSourceCode);
  24623. return;
  24624. }
  24625. // Already converted
  24626. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24627. callback(preparedSourceCode.replace("#version 300 es", ""));
  24628. return;
  24629. }
  24630. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24631. // Remove extensions
  24632. // #extension GL_OES_standard_derivatives : enable
  24633. // #extension GL_EXT_shader_texture_lod : enable
  24634. // #extension GL_EXT_frag_depth : enable
  24635. // #extension GL_EXT_draw_buffers : require
  24636. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24637. var result = preparedSourceCode.replace(regex, "");
  24638. // Migrate to GLSL v300
  24639. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24640. result = result.replace(/attribute[ \t]/g, "in ");
  24641. result = result.replace(/[ \t]attribute/g, " in");
  24642. if (isFragment) {
  24643. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24644. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24645. result = result.replace(/texture2D\(/g, "texture(");
  24646. result = result.replace(/textureCube\(/g, "texture(");
  24647. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24648. result = result.replace(/gl_FragColor/g, "glFragColor");
  24649. result = result.replace(/gl_FragData/g, "glFragData");
  24650. result = result.replace(/void\s+?main\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24651. }
  24652. callback(result);
  24653. };
  24654. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24655. var _this = this;
  24656. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24657. var match = regex.exec(sourceCode);
  24658. var returnValue = new String(sourceCode);
  24659. while (match != null) {
  24660. var includeFile = match[1];
  24661. // Uniform declaration
  24662. if (includeFile.indexOf("__decl__") !== -1) {
  24663. includeFile = includeFile.replace(/__decl__/, "");
  24664. if (this._engine.supportsUniformBuffers) {
  24665. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24666. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24667. }
  24668. includeFile = includeFile + "Declaration";
  24669. }
  24670. if (Effect.IncludesShadersStore[includeFile]) {
  24671. // Substitution
  24672. var includeContent = Effect.IncludesShadersStore[includeFile];
  24673. if (match[2]) {
  24674. var splits = match[3].split(",");
  24675. for (var index = 0; index < splits.length; index += 2) {
  24676. var source = new RegExp(splits[index], "g");
  24677. var dest = splits[index + 1];
  24678. includeContent = includeContent.replace(source, dest);
  24679. }
  24680. }
  24681. if (match[4]) {
  24682. var indexString = match[5];
  24683. if (indexString.indexOf("..") !== -1) {
  24684. var indexSplits = indexString.split("..");
  24685. var minIndex = parseInt(indexSplits[0]);
  24686. var maxIndex = parseInt(indexSplits[1]);
  24687. var sourceIncludeContent = includeContent.slice(0);
  24688. includeContent = "";
  24689. if (isNaN(maxIndex)) {
  24690. maxIndex = this._indexParameters[indexSplits[1]];
  24691. }
  24692. for (var i = minIndex; i < maxIndex; i++) {
  24693. if (!this._engine.supportsUniformBuffers) {
  24694. // Ubo replacement
  24695. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24696. return p1 + "{X}";
  24697. });
  24698. }
  24699. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24700. }
  24701. }
  24702. else {
  24703. if (!this._engine.supportsUniformBuffers) {
  24704. // Ubo replacement
  24705. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24706. return p1 + "{X}";
  24707. });
  24708. }
  24709. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24710. }
  24711. }
  24712. // Replace
  24713. returnValue = returnValue.replace(match[0], includeContent);
  24714. }
  24715. else {
  24716. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24717. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24718. Effect.IncludesShadersStore[includeFile] = fileContent;
  24719. _this._processIncludes(returnValue, callback);
  24720. });
  24721. return;
  24722. }
  24723. match = regex.exec(sourceCode);
  24724. }
  24725. callback(returnValue);
  24726. };
  24727. Effect.prototype._processPrecision = function (source) {
  24728. if (source.indexOf("precision highp float") === -1) {
  24729. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24730. source = "precision mediump float;\n" + source;
  24731. }
  24732. else {
  24733. source = "precision highp float;\n" + source;
  24734. }
  24735. }
  24736. else {
  24737. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24738. source = source.replace("precision highp float", "precision mediump float");
  24739. }
  24740. }
  24741. return source;
  24742. };
  24743. Effect.prototype._prepareEffect = function () {
  24744. var attributesNames = this._attributesNames;
  24745. var defines = this.defines;
  24746. var fallbacks = this._fallbacks;
  24747. this._valueCache = {};
  24748. try {
  24749. var engine = this._engine;
  24750. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24751. if (engine.webGLVersion > 1) {
  24752. for (var name in this._uniformBuffersNames) {
  24753. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24754. }
  24755. }
  24756. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24757. this._attributes = engine.getAttributes(this._program, attributesNames);
  24758. var index;
  24759. for (index = 0; index < this._samplers.length; index++) {
  24760. var sampler = this.getUniform(this._samplers[index]);
  24761. if (sampler == null) {
  24762. this._samplers.splice(index, 1);
  24763. index--;
  24764. }
  24765. }
  24766. engine.bindSamplers(this);
  24767. this._compilationError = "";
  24768. this._isReady = true;
  24769. if (this.onCompiled) {
  24770. this.onCompiled(this);
  24771. }
  24772. this.onCompileObservable.notifyObservers(this);
  24773. this.onCompileObservable.clear();
  24774. // Unbind mesh reference in fallbacks
  24775. if (this._fallbacks) {
  24776. this._fallbacks.unBindMesh();
  24777. }
  24778. }
  24779. catch (e) {
  24780. this._compilationError = e.message;
  24781. // Let's go through fallbacks then
  24782. BABYLON.Tools.Error("Unable to compile effect:");
  24783. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24784. return " " + uniform;
  24785. }));
  24786. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24787. return " " + attribute;
  24788. }));
  24789. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24790. BABYLON.Tools.Error("Error: " + this._compilationError);
  24791. if (fallbacks && fallbacks.isMoreFallbacks) {
  24792. BABYLON.Tools.Error("Trying next fallback.");
  24793. this.defines = fallbacks.reduce(this.defines);
  24794. this._prepareEffect();
  24795. }
  24796. else {
  24797. if (this.onError) {
  24798. this.onError(this, this._compilationError);
  24799. }
  24800. this.onErrorObservable.notifyObservers(this);
  24801. this.onErrorObservable.clear();
  24802. // Unbind mesh reference in fallbacks
  24803. if (this._fallbacks) {
  24804. this._fallbacks.unBindMesh();
  24805. }
  24806. }
  24807. }
  24808. };
  24809. Object.defineProperty(Effect.prototype, "isSupported", {
  24810. get: function () {
  24811. return this._compilationError === "";
  24812. },
  24813. enumerable: true,
  24814. configurable: true
  24815. });
  24816. Effect.prototype._bindTexture = function (channel, texture) {
  24817. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24818. };
  24819. Effect.prototype.setTexture = function (channel, texture) {
  24820. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24821. };
  24822. Effect.prototype.setTextureArray = function (channel, textures) {
  24823. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24824. var initialPos = this._samplers.indexOf(channel);
  24825. for (var index = 1; index < textures.length; index++) {
  24826. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24827. }
  24828. }
  24829. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24830. };
  24831. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24832. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24833. };
  24834. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24835. var cache = this._valueCache[uniformName];
  24836. var flag = matrix.updateFlag;
  24837. if (cache !== undefined && cache === flag) {
  24838. return false;
  24839. }
  24840. this._valueCache[uniformName] = flag;
  24841. return true;
  24842. };
  24843. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24844. var cache = this._valueCache[uniformName];
  24845. if (!cache) {
  24846. cache = [x, y];
  24847. this._valueCache[uniformName] = cache;
  24848. return true;
  24849. }
  24850. var changed = false;
  24851. if (cache[0] !== x) {
  24852. cache[0] = x;
  24853. changed = true;
  24854. }
  24855. if (cache[1] !== y) {
  24856. cache[1] = y;
  24857. changed = true;
  24858. }
  24859. return changed;
  24860. };
  24861. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24862. var cache = this._valueCache[uniformName];
  24863. if (!cache) {
  24864. cache = [x, y, z];
  24865. this._valueCache[uniformName] = cache;
  24866. return true;
  24867. }
  24868. var changed = false;
  24869. if (cache[0] !== x) {
  24870. cache[0] = x;
  24871. changed = true;
  24872. }
  24873. if (cache[1] !== y) {
  24874. cache[1] = y;
  24875. changed = true;
  24876. }
  24877. if (cache[2] !== z) {
  24878. cache[2] = z;
  24879. changed = true;
  24880. }
  24881. return changed;
  24882. };
  24883. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24884. var cache = this._valueCache[uniformName];
  24885. if (!cache) {
  24886. cache = [x, y, z, w];
  24887. this._valueCache[uniformName] = cache;
  24888. return true;
  24889. }
  24890. var changed = false;
  24891. if (cache[0] !== x) {
  24892. cache[0] = x;
  24893. changed = true;
  24894. }
  24895. if (cache[1] !== y) {
  24896. cache[1] = y;
  24897. changed = true;
  24898. }
  24899. if (cache[2] !== z) {
  24900. cache[2] = z;
  24901. changed = true;
  24902. }
  24903. if (cache[3] !== w) {
  24904. cache[3] = w;
  24905. changed = true;
  24906. }
  24907. return changed;
  24908. };
  24909. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24910. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24911. return;
  24912. }
  24913. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24914. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24915. };
  24916. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24917. this._engine.bindUniformBlock(this._program, blockName, index);
  24918. };
  24919. Effect.prototype.setIntArray = function (uniformName, array) {
  24920. this._valueCache[uniformName] = null;
  24921. this._engine.setIntArray(this.getUniform(uniformName), array);
  24922. return this;
  24923. };
  24924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24925. this._valueCache[uniformName] = null;
  24926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24927. return this;
  24928. };
  24929. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24930. this._valueCache[uniformName] = null;
  24931. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24932. return this;
  24933. };
  24934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24935. this._valueCache[uniformName] = null;
  24936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24937. return this;
  24938. };
  24939. Effect.prototype.setFloatArray = function (uniformName, array) {
  24940. this._valueCache[uniformName] = null;
  24941. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24942. return this;
  24943. };
  24944. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24945. this._valueCache[uniformName] = null;
  24946. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24947. return this;
  24948. };
  24949. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24950. this._valueCache[uniformName] = null;
  24951. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24952. return this;
  24953. };
  24954. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24955. this._valueCache[uniformName] = null;
  24956. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24957. return this;
  24958. };
  24959. Effect.prototype.setArray = function (uniformName, array) {
  24960. this._valueCache[uniformName] = null;
  24961. this._engine.setArray(this.getUniform(uniformName), array);
  24962. return this;
  24963. };
  24964. Effect.prototype.setArray2 = function (uniformName, array) {
  24965. this._valueCache[uniformName] = null;
  24966. this._engine.setArray2(this.getUniform(uniformName), array);
  24967. return this;
  24968. };
  24969. Effect.prototype.setArray3 = function (uniformName, array) {
  24970. this._valueCache[uniformName] = null;
  24971. this._engine.setArray3(this.getUniform(uniformName), array);
  24972. return this;
  24973. };
  24974. Effect.prototype.setArray4 = function (uniformName, array) {
  24975. this._valueCache[uniformName] = null;
  24976. this._engine.setArray4(this.getUniform(uniformName), array);
  24977. return this;
  24978. };
  24979. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24980. if (!matrices) {
  24981. return;
  24982. }
  24983. this._valueCache[uniformName] = null;
  24984. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24985. return this;
  24986. };
  24987. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24988. if (this._cacheMatrix(uniformName, matrix)) {
  24989. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24990. }
  24991. return this;
  24992. };
  24993. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24994. this._valueCache[uniformName] = null;
  24995. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24996. return this;
  24997. };
  24998. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24999. this._valueCache[uniformName] = null;
  25000. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25001. return this;
  25002. };
  25003. Effect.prototype.setFloat = function (uniformName, value) {
  25004. var cache = this._valueCache[uniformName];
  25005. if (cache !== undefined && cache === value)
  25006. return this;
  25007. this._valueCache[uniformName] = value;
  25008. this._engine.setFloat(this.getUniform(uniformName), value);
  25009. return this;
  25010. };
  25011. Effect.prototype.setBool = function (uniformName, bool) {
  25012. var cache = this._valueCache[uniformName];
  25013. if (cache !== undefined && cache === bool)
  25014. return this;
  25015. this._valueCache[uniformName] = bool;
  25016. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25017. return this;
  25018. };
  25019. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25020. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25021. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25022. }
  25023. return this;
  25024. };
  25025. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25026. if (this._cacheFloat2(uniformName, x, y)) {
  25027. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25028. }
  25029. return this;
  25030. };
  25031. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25032. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25033. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25034. }
  25035. return this;
  25036. };
  25037. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25038. if (this._cacheFloat3(uniformName, x, y, z)) {
  25039. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25040. }
  25041. return this;
  25042. };
  25043. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25044. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25045. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25046. }
  25047. return this;
  25048. };
  25049. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25050. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25051. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25052. }
  25053. return this;
  25054. };
  25055. Effect.prototype.setColor3 = function (uniformName, color3) {
  25056. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25057. this._engine.setColor3(this.getUniform(uniformName), color3);
  25058. }
  25059. return this;
  25060. };
  25061. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25062. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25063. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25064. }
  25065. return this;
  25066. };
  25067. Effect.ResetCache = function () {
  25068. Effect._baseCache = {};
  25069. };
  25070. Effect._uniqueIdSeed = 0;
  25071. Effect._baseCache = {};
  25072. // Statics
  25073. Effect.ShadersStore = {};
  25074. Effect.IncludesShadersStore = {};
  25075. return Effect;
  25076. }());
  25077. BABYLON.Effect = Effect;
  25078. })(BABYLON || (BABYLON = {}));
  25079. //# sourceMappingURL=babylon.effect.js.map
  25080. var BABYLON;
  25081. (function (BABYLON) {
  25082. var MaterialHelper = (function () {
  25083. function MaterialHelper() {
  25084. }
  25085. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25086. defines._needUVs = true;
  25087. defines[key] = true;
  25088. if (texture.getTextureMatrix().isIdentity(true)) {
  25089. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25090. if (texture.coordinatesIndex === 0) {
  25091. defines["MAINUV1"] = true;
  25092. }
  25093. else {
  25094. defines["MAINUV2"] = true;
  25095. }
  25096. }
  25097. else {
  25098. defines[key + "DIRECTUV"] = 0;
  25099. }
  25100. };
  25101. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25102. var matrix = texture.getTextureMatrix();
  25103. if (!matrix.isIdentity(true)) {
  25104. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25105. }
  25106. };
  25107. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25108. if (defines._areMiscDirty) {
  25109. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25110. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25111. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25112. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  25113. }
  25114. };
  25115. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25116. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25117. var changed = false;
  25118. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25119. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25120. changed = true;
  25121. }
  25122. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25123. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25124. changed = true;
  25125. }
  25126. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25127. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25128. changed = true;
  25129. }
  25130. if (defines["INSTANCES"] !== useInstances) {
  25131. defines["INSTANCES"] = useInstances;
  25132. changed = true;
  25133. }
  25134. if (changed) {
  25135. defines.markAsUnprocessed();
  25136. }
  25137. };
  25138. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25139. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25140. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25141. return false;
  25142. }
  25143. defines._normals = defines._needNormals;
  25144. defines._uvs = defines._needUVs;
  25145. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25146. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25147. defines["TANGENT"] = true;
  25148. }
  25149. if (defines._needUVs) {
  25150. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25151. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25152. }
  25153. else {
  25154. defines["UV1"] = false;
  25155. defines["UV2"] = false;
  25156. }
  25157. if (useVertexColor) {
  25158. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25159. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25160. }
  25161. if (useBones) {
  25162. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25163. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25164. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25165. }
  25166. else {
  25167. defines["NUM_BONE_INFLUENCERS"] = 0;
  25168. defines["BonesPerMesh"] = 0;
  25169. }
  25170. }
  25171. if (useMorphTargets) {
  25172. if (mesh.morphTargetManager) {
  25173. var manager = mesh.morphTargetManager;
  25174. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25175. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25176. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25177. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25178. }
  25179. else {
  25180. defines["MORPHTARGETS_TANGENT"] = false;
  25181. defines["MORPHTARGETS_NORMAL"] = false;
  25182. defines["MORPHTARGETS"] = false;
  25183. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25184. }
  25185. }
  25186. return true;
  25187. };
  25188. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25189. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25190. if (disableLighting === void 0) { disableLighting = false; }
  25191. if (!defines._areLightsDirty) {
  25192. return defines._needNormals;
  25193. }
  25194. var lightIndex = 0;
  25195. var needNormals = false;
  25196. var needRebuild = false;
  25197. var lightmapMode = false;
  25198. var shadowEnabled = false;
  25199. var specularEnabled = false;
  25200. if (scene.lightsEnabled && !disableLighting) {
  25201. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25202. var light = _a[_i];
  25203. needNormals = true;
  25204. if (defines["LIGHT" + lightIndex] === undefined) {
  25205. needRebuild = true;
  25206. }
  25207. defines["LIGHT" + lightIndex] = true;
  25208. defines["SPOTLIGHT" + lightIndex] = false;
  25209. defines["HEMILIGHT" + lightIndex] = false;
  25210. defines["POINTLIGHT" + lightIndex] = false;
  25211. defines["DIRLIGHT" + lightIndex] = false;
  25212. var type;
  25213. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25214. type = "SPOTLIGHT" + lightIndex;
  25215. }
  25216. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25217. type = "HEMILIGHT" + lightIndex;
  25218. }
  25219. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25220. type = "POINTLIGHT" + lightIndex;
  25221. }
  25222. else {
  25223. type = "DIRLIGHT" + lightIndex;
  25224. }
  25225. defines[type] = true;
  25226. // Specular
  25227. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25228. specularEnabled = true;
  25229. }
  25230. // Shadows
  25231. defines["SHADOW" + lightIndex] = false;
  25232. defines["SHADOWPCF" + lightIndex] = false;
  25233. defines["SHADOWESM" + lightIndex] = false;
  25234. defines["SHADOWCUBE" + lightIndex] = false;
  25235. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25236. var shadowGenerator = light.getShadowGenerator();
  25237. if (shadowGenerator) {
  25238. shadowEnabled = true;
  25239. shadowGenerator.prepareDefines(defines, lightIndex);
  25240. }
  25241. }
  25242. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25243. lightmapMode = true;
  25244. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25245. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25246. }
  25247. else {
  25248. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25249. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25250. }
  25251. lightIndex++;
  25252. if (lightIndex === maxSimultaneousLights)
  25253. break;
  25254. }
  25255. }
  25256. defines["SPECULARTERM"] = specularEnabled;
  25257. defines["SHADOWS"] = shadowEnabled;
  25258. // Resetting all other lights if any
  25259. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25260. if (defines["LIGHT" + index] !== undefined) {
  25261. defines["LIGHT" + index] = false;
  25262. defines["HEMILIGHT" + lightIndex] = false;
  25263. defines["POINTLIGHT" + lightIndex] = false;
  25264. defines["DIRLIGHT" + lightIndex] = false;
  25265. defines["SPOTLIGHT" + lightIndex] = false;
  25266. defines["SHADOW" + lightIndex] = false;
  25267. }
  25268. }
  25269. var caps = scene.getEngine().getCaps();
  25270. if (defines["SHADOWFLOAT"] === undefined) {
  25271. needRebuild = true;
  25272. }
  25273. defines["SHADOWFLOAT"] = shadowEnabled &&
  25274. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25275. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25276. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25277. if (needRebuild) {
  25278. defines.rebuild();
  25279. }
  25280. return needNormals;
  25281. };
  25282. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25283. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25284. var uniformsList, uniformBuffersList, samplersList, defines;
  25285. if (uniformsListOrOptions.uniformsNames) {
  25286. var options = uniformsListOrOptions;
  25287. uniformsList = options.uniformsNames;
  25288. uniformBuffersList = options.uniformBuffersNames;
  25289. samplersList = options.samplers;
  25290. defines = options.defines;
  25291. maxSimultaneousLights = options.maxSimultaneousLights;
  25292. }
  25293. else {
  25294. uniformsList = uniformsListOrOptions;
  25295. }
  25296. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25297. if (!defines["LIGHT" + lightIndex]) {
  25298. break;
  25299. }
  25300. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25301. if (uniformBuffersList) {
  25302. uniformBuffersList.push("Light" + lightIndex);
  25303. }
  25304. samplersList.push("shadowSampler" + lightIndex);
  25305. }
  25306. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25307. uniformsList.push("morphTargetInfluences");
  25308. }
  25309. };
  25310. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25311. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25312. if (!defines["SHADOWS"]) {
  25313. return;
  25314. }
  25315. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25316. if (!defines["LIGHT" + lightIndex]) {
  25317. break;
  25318. }
  25319. if (lightIndex > 0) {
  25320. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25321. }
  25322. if (defines["SHADOW" + lightIndex]) {
  25323. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25324. }
  25325. if (defines["SHADOWPCF" + lightIndex]) {
  25326. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25327. }
  25328. if (defines["SHADOWESM" + lightIndex]) {
  25329. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25330. }
  25331. }
  25332. };
  25333. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25334. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25335. if (influencers > 0) {
  25336. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25337. var manager = mesh.morphTargetManager;
  25338. var normal = manager.supportsNormals && defines["NORMAL"];
  25339. var tangent = manager.supportsTangents && defines["TANGENT"];
  25340. for (var index = 0; index < influencers; index++) {
  25341. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25342. if (normal) {
  25343. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25344. }
  25345. if (tangent) {
  25346. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25347. }
  25348. if (attribs.length > maxAttributesCount) {
  25349. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25350. }
  25351. }
  25352. }
  25353. };
  25354. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25355. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25356. fallbacks.addCPUSkinningFallback(0, mesh);
  25357. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25358. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25359. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25362. }
  25363. }
  25364. };
  25365. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25366. if (defines["INSTANCES"]) {
  25367. attribs.push("world0");
  25368. attribs.push("world1");
  25369. attribs.push("world2");
  25370. attribs.push("world3");
  25371. }
  25372. };
  25373. // Bindings
  25374. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25375. if (light.shadowEnabled && mesh.receiveShadows) {
  25376. var shadowGenerator = light.getShadowGenerator();
  25377. if (shadowGenerator) {
  25378. shadowGenerator.bindShadowLight(lightIndex, effect);
  25379. }
  25380. }
  25381. };
  25382. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25383. light.transferToEffect(effect, lightIndex + "");
  25384. };
  25385. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25386. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25387. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25388. var lightIndex = 0;
  25389. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25390. var light = _a[_i];
  25391. var scaledIntensity = light.getScaledIntensity();
  25392. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25393. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25394. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25395. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25396. if (defines["SPECULARTERM"]) {
  25397. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25398. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25399. }
  25400. // Shadows
  25401. if (scene.shadowsEnabled) {
  25402. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25403. }
  25404. light._uniformBuffer.update();
  25405. lightIndex++;
  25406. if (lightIndex === maxSimultaneousLights)
  25407. break;
  25408. }
  25409. };
  25410. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25411. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25412. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25413. effect.setColor3("vFogColor", scene.fogColor);
  25414. }
  25415. };
  25416. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25417. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25418. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25419. if (matrices) {
  25420. effect.setMatrices("mBones", matrices);
  25421. }
  25422. }
  25423. };
  25424. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25425. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25426. return;
  25427. }
  25428. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25429. };
  25430. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25431. if (defines["LOGARITHMICDEPTH"]) {
  25432. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25433. }
  25434. };
  25435. MaterialHelper.BindClipPlane = function (effect, scene) {
  25436. if (scene.clipPlane) {
  25437. var clipPlane = scene.clipPlane;
  25438. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25439. }
  25440. };
  25441. return MaterialHelper;
  25442. }());
  25443. BABYLON.MaterialHelper = MaterialHelper;
  25444. })(BABYLON || (BABYLON = {}));
  25445. //# sourceMappingURL=babylon.materialHelper.js.map
  25446. var BABYLON;
  25447. (function (BABYLON) {
  25448. var MaterialDefines = (function () {
  25449. function MaterialDefines() {
  25450. this._isDirty = true;
  25451. this._areLightsDirty = true;
  25452. this._areAttributesDirty = true;
  25453. this._areTexturesDirty = true;
  25454. this._areFresnelDirty = true;
  25455. this._areMiscDirty = true;
  25456. this._areImageProcessingDirty = true;
  25457. this._normals = false;
  25458. this._uvs = false;
  25459. this._needNormals = false;
  25460. this._needUVs = false;
  25461. }
  25462. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25463. get: function () {
  25464. return this._isDirty;
  25465. },
  25466. enumerable: true,
  25467. configurable: true
  25468. });
  25469. MaterialDefines.prototype.markAsProcessed = function () {
  25470. this._isDirty = false;
  25471. this._areAttributesDirty = false;
  25472. this._areTexturesDirty = false;
  25473. this._areFresnelDirty = false;
  25474. this._areLightsDirty = false;
  25475. this._areMiscDirty = false;
  25476. this._areImageProcessingDirty = false;
  25477. };
  25478. MaterialDefines.prototype.markAsUnprocessed = function () {
  25479. this._isDirty = true;
  25480. };
  25481. MaterialDefines.prototype.markAllAsDirty = function () {
  25482. this._areTexturesDirty = true;
  25483. this._areAttributesDirty = true;
  25484. this._areLightsDirty = true;
  25485. this._areFresnelDirty = true;
  25486. this._areMiscDirty = true;
  25487. this._areImageProcessingDirty = true;
  25488. this._isDirty = true;
  25489. };
  25490. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25491. this._areImageProcessingDirty = true;
  25492. this._isDirty = true;
  25493. };
  25494. MaterialDefines.prototype.markAsLightDirty = function () {
  25495. this._areLightsDirty = true;
  25496. this._isDirty = true;
  25497. };
  25498. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25499. this._areAttributesDirty = true;
  25500. this._isDirty = true;
  25501. };
  25502. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25503. this._areTexturesDirty = true;
  25504. this._isDirty = true;
  25505. };
  25506. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25507. this._areFresnelDirty = true;
  25508. this._isDirty = true;
  25509. };
  25510. MaterialDefines.prototype.markAsMiscDirty = function () {
  25511. this._areMiscDirty = true;
  25512. this._isDirty = true;
  25513. };
  25514. MaterialDefines.prototype.rebuild = function () {
  25515. if (this._keys) {
  25516. delete this._keys;
  25517. }
  25518. this._keys = [];
  25519. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25520. var key = _a[_i];
  25521. if (key[0] === "_") {
  25522. continue;
  25523. }
  25524. this._keys.push(key);
  25525. }
  25526. };
  25527. MaterialDefines.prototype.isEqual = function (other) {
  25528. if (this._keys.length !== other._keys.length) {
  25529. return false;
  25530. }
  25531. for (var index = 0; index < this._keys.length; index++) {
  25532. var prop = this._keys[index];
  25533. if (this[prop] !== other[prop]) {
  25534. return false;
  25535. }
  25536. }
  25537. return true;
  25538. };
  25539. MaterialDefines.prototype.cloneTo = function (other) {
  25540. if (this._keys.length !== other._keys.length) {
  25541. other._keys = this._keys.slice(0);
  25542. }
  25543. for (var index = 0; index < this._keys.length; index++) {
  25544. var prop = this._keys[index];
  25545. other[prop] = this[prop];
  25546. }
  25547. };
  25548. MaterialDefines.prototype.reset = function () {
  25549. for (var index = 0; index < this._keys.length; index++) {
  25550. var prop = this._keys[index];
  25551. if (typeof (this[prop]) === "number") {
  25552. this[prop] = 0;
  25553. }
  25554. else {
  25555. this[prop] = false;
  25556. }
  25557. }
  25558. };
  25559. MaterialDefines.prototype.toString = function () {
  25560. var result = "";
  25561. for (var index = 0; index < this._keys.length; index++) {
  25562. var prop = this._keys[index];
  25563. var value = this[prop];
  25564. if (typeof (value) === "number") {
  25565. result += "#define " + prop + " " + this[prop] + "\n";
  25566. }
  25567. else if (value) {
  25568. result += "#define " + prop + "\n";
  25569. }
  25570. }
  25571. return result;
  25572. };
  25573. return MaterialDefines;
  25574. }());
  25575. BABYLON.MaterialDefines = MaterialDefines;
  25576. var Material = (function () {
  25577. function Material(name, scene, doNotAdd) {
  25578. this.checkReadyOnEveryCall = false;
  25579. this.checkReadyOnlyOnce = false;
  25580. this.state = "";
  25581. this.alpha = 1.0;
  25582. this._backFaceCulling = true;
  25583. this.doNotSerialize = false;
  25584. this.storeEffectOnSubMeshes = false;
  25585. /**
  25586. * An event triggered when the material is disposed.
  25587. * @type {BABYLON.Observable}
  25588. */
  25589. this.onDisposeObservable = new BABYLON.Observable();
  25590. /**
  25591. * An event triggered when the material is bound.
  25592. * @type {BABYLON.Observable}
  25593. */
  25594. this.onBindObservable = new BABYLON.Observable();
  25595. /**
  25596. * An event triggered when the material is unbound.
  25597. * @type {BABYLON.Observable}
  25598. */
  25599. this.onUnBindObservable = new BABYLON.Observable();
  25600. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25601. this.needDepthPrePass = false;
  25602. this.disableDepthWrite = false;
  25603. this._fogEnabled = true;
  25604. this.pointSize = 1.0;
  25605. this.zOffset = 0;
  25606. this._wasPreviouslyReady = false;
  25607. this._fillMode = Material.TriangleFillMode;
  25608. this.name = name;
  25609. this.id = name || BABYLON.Tools.RandomId();
  25610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25611. if (this._scene.useRightHandedSystem) {
  25612. this.sideOrientation = Material.ClockWiseSideOrientation;
  25613. }
  25614. else {
  25615. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25616. }
  25617. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25618. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25619. if (!doNotAdd) {
  25620. this._scene.materials.push(this);
  25621. }
  25622. }
  25623. Object.defineProperty(Material, "TriangleFillMode", {
  25624. get: function () {
  25625. return Material._TriangleFillMode;
  25626. },
  25627. enumerable: true,
  25628. configurable: true
  25629. });
  25630. Object.defineProperty(Material, "WireFrameFillMode", {
  25631. get: function () {
  25632. return Material._WireFrameFillMode;
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. Object.defineProperty(Material, "PointFillMode", {
  25638. get: function () {
  25639. return Material._PointFillMode;
  25640. },
  25641. enumerable: true,
  25642. configurable: true
  25643. });
  25644. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25645. get: function () {
  25646. return Material._ClockWiseSideOrientation;
  25647. },
  25648. enumerable: true,
  25649. configurable: true
  25650. });
  25651. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25652. get: function () {
  25653. return Material._CounterClockWiseSideOrientation;
  25654. },
  25655. enumerable: true,
  25656. configurable: true
  25657. });
  25658. Object.defineProperty(Material, "TextureDirtyFlag", {
  25659. get: function () {
  25660. return Material._TextureDirtyFlag;
  25661. },
  25662. enumerable: true,
  25663. configurable: true
  25664. });
  25665. Object.defineProperty(Material, "LightDirtyFlag", {
  25666. get: function () {
  25667. return Material._LightDirtyFlag;
  25668. },
  25669. enumerable: true,
  25670. configurable: true
  25671. });
  25672. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25673. get: function () {
  25674. return Material._FresnelDirtyFlag;
  25675. },
  25676. enumerable: true,
  25677. configurable: true
  25678. });
  25679. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25680. get: function () {
  25681. return Material._AttributesDirtyFlag;
  25682. },
  25683. enumerable: true,
  25684. configurable: true
  25685. });
  25686. Object.defineProperty(Material, "MiscDirtyFlag", {
  25687. get: function () {
  25688. return Material._MiscDirtyFlag;
  25689. },
  25690. enumerable: true,
  25691. configurable: true
  25692. });
  25693. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25694. get: function () {
  25695. return this._backFaceCulling;
  25696. },
  25697. set: function (value) {
  25698. if (this._backFaceCulling === value) {
  25699. return;
  25700. }
  25701. this._backFaceCulling = value;
  25702. this.markAsDirty(Material.TextureDirtyFlag);
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. Object.defineProperty(Material.prototype, "onDispose", {
  25708. set: function (callback) {
  25709. if (this._onDisposeObserver) {
  25710. this.onDisposeObservable.remove(this._onDisposeObserver);
  25711. }
  25712. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25713. },
  25714. enumerable: true,
  25715. configurable: true
  25716. });
  25717. Object.defineProperty(Material.prototype, "onBind", {
  25718. set: function (callback) {
  25719. if (this._onBindObserver) {
  25720. this.onBindObservable.remove(this._onBindObserver);
  25721. }
  25722. this._onBindObserver = this.onBindObservable.add(callback);
  25723. },
  25724. enumerable: true,
  25725. configurable: true
  25726. });
  25727. Object.defineProperty(Material.prototype, "fogEnabled", {
  25728. get: function () {
  25729. return this._fogEnabled;
  25730. },
  25731. set: function (value) {
  25732. if (this._fogEnabled === value) {
  25733. return;
  25734. }
  25735. this._fogEnabled = value;
  25736. this.markAsDirty(Material.MiscDirtyFlag);
  25737. },
  25738. enumerable: true,
  25739. configurable: true
  25740. });
  25741. Object.defineProperty(Material.prototype, "wireframe", {
  25742. get: function () {
  25743. return this._fillMode === Material.WireFrameFillMode;
  25744. },
  25745. set: function (value) {
  25746. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25747. },
  25748. enumerable: true,
  25749. configurable: true
  25750. });
  25751. Object.defineProperty(Material.prototype, "pointsCloud", {
  25752. get: function () {
  25753. return this._fillMode === Material.PointFillMode;
  25754. },
  25755. set: function (value) {
  25756. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25757. },
  25758. enumerable: true,
  25759. configurable: true
  25760. });
  25761. Object.defineProperty(Material.prototype, "fillMode", {
  25762. get: function () {
  25763. return this._fillMode;
  25764. },
  25765. set: function (value) {
  25766. if (this._fillMode === value) {
  25767. return;
  25768. }
  25769. this._fillMode = value;
  25770. this.markAsDirty(Material.MiscDirtyFlag);
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. /**
  25776. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25777. * subclasses should override adding information pertainent to themselves
  25778. */
  25779. Material.prototype.toString = function (fullDetails) {
  25780. var ret = "Name: " + this.name;
  25781. if (fullDetails) {
  25782. }
  25783. return ret;
  25784. };
  25785. /**
  25786. * Child classes can use it to update shaders
  25787. */
  25788. Material.prototype.getClassName = function () {
  25789. return "Material";
  25790. };
  25791. Object.defineProperty(Material.prototype, "isFrozen", {
  25792. get: function () {
  25793. return this.checkReadyOnlyOnce;
  25794. },
  25795. enumerable: true,
  25796. configurable: true
  25797. });
  25798. Material.prototype.freeze = function () {
  25799. this.checkReadyOnlyOnce = true;
  25800. };
  25801. Material.prototype.unfreeze = function () {
  25802. this.checkReadyOnlyOnce = false;
  25803. };
  25804. Material.prototype.isReady = function (mesh, useInstances) {
  25805. return true;
  25806. };
  25807. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25808. return false;
  25809. };
  25810. Material.prototype.getEffect = function () {
  25811. return this._effect;
  25812. };
  25813. Material.prototype.getScene = function () {
  25814. return this._scene;
  25815. };
  25816. Material.prototype.needAlphaBlending = function () {
  25817. return (this.alpha < 1.0);
  25818. };
  25819. Material.prototype.needAlphaTesting = function () {
  25820. return false;
  25821. };
  25822. Material.prototype.getAlphaTestTexture = function () {
  25823. return null;
  25824. };
  25825. Material.prototype.markDirty = function () {
  25826. this._wasPreviouslyReady = false;
  25827. };
  25828. Material.prototype._preBind = function (effect) {
  25829. var engine = this._scene.getEngine();
  25830. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25831. engine.enableEffect(effect ? effect : this._effect);
  25832. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25833. };
  25834. Material.prototype.bind = function (world, mesh) {
  25835. };
  25836. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25837. };
  25838. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25839. };
  25840. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25841. sceneUbo.bindToEffect(effect, "Scene");
  25842. };
  25843. Material.prototype.bindView = function (effect) {
  25844. if (!this._useUBO) {
  25845. effect.setMatrix("view", this.getScene().getViewMatrix());
  25846. }
  25847. else {
  25848. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25849. }
  25850. };
  25851. Material.prototype.bindViewProjection = function (effect) {
  25852. if (!this._useUBO) {
  25853. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25854. }
  25855. else {
  25856. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25857. }
  25858. };
  25859. Material.prototype._afterBind = function (mesh) {
  25860. this._scene._cachedMaterial = this;
  25861. if (mesh) {
  25862. this._scene._cachedVisibility = mesh.visibility;
  25863. }
  25864. else {
  25865. this._scene._cachedVisibility = 1;
  25866. }
  25867. this.onBindObservable.notifyObservers(mesh);
  25868. if (this.disableDepthWrite) {
  25869. var engine = this._scene.getEngine();
  25870. this._cachedDepthWriteState = engine.getDepthWrite();
  25871. engine.setDepthWrite(false);
  25872. }
  25873. };
  25874. Material.prototype.unbind = function () {
  25875. this.onUnBindObservable.notifyObservers(this);
  25876. if (this.disableDepthWrite) {
  25877. var engine = this._scene.getEngine();
  25878. engine.setDepthWrite(this._cachedDepthWriteState);
  25879. }
  25880. };
  25881. Material.prototype.getActiveTextures = function () {
  25882. return [];
  25883. };
  25884. Material.prototype.hasTexture = function (texture) {
  25885. return false;
  25886. };
  25887. Material.prototype.clone = function (name) {
  25888. return null;
  25889. };
  25890. Material.prototype.getBindedMeshes = function () {
  25891. var result = new Array();
  25892. for (var index = 0; index < this._scene.meshes.length; index++) {
  25893. var mesh = this._scene.meshes[index];
  25894. if (mesh.material === this) {
  25895. result.push(mesh);
  25896. }
  25897. }
  25898. return result;
  25899. };
  25900. /**
  25901. * Force shader compilation including textures ready check
  25902. */
  25903. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25904. var _this = this;
  25905. var subMesh = new BABYLON.BaseSubMesh();
  25906. var scene = this.getScene();
  25907. var engine = scene.getEngine();
  25908. var checkReady = function () {
  25909. if (!_this._scene || !_this._scene.getEngine()) {
  25910. return;
  25911. }
  25912. if (subMesh._materialDefines) {
  25913. subMesh._materialDefines._renderId = -1;
  25914. }
  25915. var alphaTestState = engine.getAlphaTesting();
  25916. var clipPlaneState = scene.clipPlane;
  25917. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25918. if (options && options.clipPlane) {
  25919. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25920. }
  25921. if (_this.storeEffectOnSubMeshes) {
  25922. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25923. if (onCompiled) {
  25924. onCompiled(_this);
  25925. }
  25926. }
  25927. else {
  25928. setTimeout(checkReady, 16);
  25929. }
  25930. }
  25931. else {
  25932. if (_this.isReady(mesh)) {
  25933. if (onCompiled) {
  25934. onCompiled(_this);
  25935. }
  25936. }
  25937. else {
  25938. setTimeout(checkReady, 16);
  25939. }
  25940. }
  25941. engine.setAlphaTesting(alphaTestState);
  25942. if (options && options.clipPlane) {
  25943. scene.clipPlane = clipPlaneState;
  25944. }
  25945. };
  25946. checkReady();
  25947. };
  25948. Material.prototype.markAsDirty = function (flag) {
  25949. if (flag & Material.TextureDirtyFlag) {
  25950. this._markAllSubMeshesAsTexturesDirty();
  25951. }
  25952. if (flag & Material.LightDirtyFlag) {
  25953. this._markAllSubMeshesAsLightsDirty();
  25954. }
  25955. if (flag & Material.FresnelDirtyFlag) {
  25956. this._markAllSubMeshesAsFresnelDirty();
  25957. }
  25958. if (flag & Material.AttributesDirtyFlag) {
  25959. this._markAllSubMeshesAsAttributesDirty();
  25960. }
  25961. if (flag & Material.MiscDirtyFlag) {
  25962. this._markAllSubMeshesAsMiscDirty();
  25963. }
  25964. this.getScene().resetCachedMaterial();
  25965. };
  25966. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25967. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25968. var mesh = _a[_i];
  25969. if (!mesh.subMeshes) {
  25970. continue;
  25971. }
  25972. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25973. var subMesh = _c[_b];
  25974. if (subMesh.getMaterial() !== this) {
  25975. continue;
  25976. }
  25977. if (!subMesh._materialDefines) {
  25978. continue;
  25979. }
  25980. func(subMesh._materialDefines);
  25981. }
  25982. }
  25983. };
  25984. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25985. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25986. };
  25987. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25988. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25989. };
  25990. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25991. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25992. };
  25993. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25994. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25995. };
  25996. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25997. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25998. };
  25999. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26000. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26001. };
  26002. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26003. // Animations
  26004. this.getScene().stopAnimation(this);
  26005. // Remove from scene
  26006. var index = this._scene.materials.indexOf(this);
  26007. if (index >= 0) {
  26008. this._scene.materials.splice(index, 1);
  26009. }
  26010. // Remove from meshes
  26011. for (index = 0; index < this._scene.meshes.length; index++) {
  26012. var mesh = this._scene.meshes[index];
  26013. if (mesh.material === this) {
  26014. mesh.material = null;
  26015. if (mesh.geometry) {
  26016. var geometry = mesh.geometry;
  26017. if (this.storeEffectOnSubMeshes) {
  26018. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26019. var subMesh = _a[_i];
  26020. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26021. }
  26022. }
  26023. else {
  26024. geometry._releaseVertexArrayObject(this._effect);
  26025. }
  26026. }
  26027. }
  26028. }
  26029. this._uniformBuffer.dispose();
  26030. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26031. if (forceDisposeEffect && this._effect) {
  26032. if (this.storeEffectOnSubMeshes) {
  26033. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26034. var subMesh = _c[_b];
  26035. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26036. }
  26037. }
  26038. else {
  26039. this._scene.getEngine()._releaseEffect(this._effect);
  26040. }
  26041. this._effect = null;
  26042. }
  26043. // Callback
  26044. this.onDisposeObservable.notifyObservers(this);
  26045. this.onDisposeObservable.clear();
  26046. this.onBindObservable.clear();
  26047. this.onUnBindObservable.clear();
  26048. };
  26049. Material.prototype.serialize = function () {
  26050. return BABYLON.SerializationHelper.Serialize(this);
  26051. };
  26052. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26053. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26054. multiMaterial.id = parsedMultiMaterial.id;
  26055. if (BABYLON.Tags) {
  26056. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26057. }
  26058. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26059. var subMatId = parsedMultiMaterial.materials[matIndex];
  26060. if (subMatId) {
  26061. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26062. }
  26063. else {
  26064. multiMaterial.subMaterials.push(null);
  26065. }
  26066. }
  26067. return multiMaterial;
  26068. };
  26069. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26070. if (!parsedMaterial.customType) {
  26071. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26072. }
  26073. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26074. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26075. if (!BABYLON.LegacyPBRMaterial) {
  26076. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26077. return;
  26078. }
  26079. }
  26080. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26081. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26082. ;
  26083. };
  26084. Material._TriangleFillMode = 0;
  26085. Material._WireFrameFillMode = 1;
  26086. Material._PointFillMode = 2;
  26087. Material._ClockWiseSideOrientation = 0;
  26088. Material._CounterClockWiseSideOrientation = 1;
  26089. Material._TextureDirtyFlag = 1;
  26090. Material._LightDirtyFlag = 2;
  26091. Material._FresnelDirtyFlag = 4;
  26092. Material._AttributesDirtyFlag = 8;
  26093. Material._MiscDirtyFlag = 16;
  26094. __decorate([
  26095. BABYLON.serialize()
  26096. ], Material.prototype, "id", void 0);
  26097. __decorate([
  26098. BABYLON.serialize()
  26099. ], Material.prototype, "name", void 0);
  26100. __decorate([
  26101. BABYLON.serialize()
  26102. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26103. __decorate([
  26104. BABYLON.serialize()
  26105. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26106. __decorate([
  26107. BABYLON.serialize()
  26108. ], Material.prototype, "state", void 0);
  26109. __decorate([
  26110. BABYLON.serialize()
  26111. ], Material.prototype, "alpha", void 0);
  26112. __decorate([
  26113. BABYLON.serialize("backFaceCulling")
  26114. ], Material.prototype, "_backFaceCulling", void 0);
  26115. __decorate([
  26116. BABYLON.serialize()
  26117. ], Material.prototype, "sideOrientation", void 0);
  26118. __decorate([
  26119. BABYLON.serialize()
  26120. ], Material.prototype, "alphaMode", void 0);
  26121. __decorate([
  26122. BABYLON.serialize()
  26123. ], Material.prototype, "needDepthPrePass", void 0);
  26124. __decorate([
  26125. BABYLON.serialize()
  26126. ], Material.prototype, "disableDepthWrite", void 0);
  26127. __decorate([
  26128. BABYLON.serialize("fogEnabled")
  26129. ], Material.prototype, "_fogEnabled", void 0);
  26130. __decorate([
  26131. BABYLON.serialize()
  26132. ], Material.prototype, "pointSize", void 0);
  26133. __decorate([
  26134. BABYLON.serialize()
  26135. ], Material.prototype, "zOffset", void 0);
  26136. __decorate([
  26137. BABYLON.serialize()
  26138. ], Material.prototype, "wireframe", null);
  26139. __decorate([
  26140. BABYLON.serialize()
  26141. ], Material.prototype, "pointsCloud", null);
  26142. __decorate([
  26143. BABYLON.serialize()
  26144. ], Material.prototype, "fillMode", null);
  26145. return Material;
  26146. }());
  26147. BABYLON.Material = Material;
  26148. })(BABYLON || (BABYLON = {}));
  26149. //# sourceMappingURL=babylon.material.js.map
  26150. var BABYLON;
  26151. (function (BABYLON) {
  26152. var UniformBuffer = (function () {
  26153. /**
  26154. * Uniform buffer objects.
  26155. *
  26156. * Handles blocks of uniform on the GPU.
  26157. *
  26158. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26159. *
  26160. * For more information, please refer to :
  26161. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26162. */
  26163. function UniformBuffer(engine, data, dynamic) {
  26164. this._engine = engine;
  26165. this._noUBO = !engine.supportsUniformBuffers;
  26166. this._dynamic = dynamic;
  26167. this._data = data || [];
  26168. this._uniformLocations = {};
  26169. this._uniformSizes = {};
  26170. this._uniformLocationPointer = 0;
  26171. this._needSync = false;
  26172. if (this._noUBO) {
  26173. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26174. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26175. this.updateFloat = this._updateFloatForEffect;
  26176. this.updateFloat2 = this._updateFloat2ForEffect;
  26177. this.updateFloat3 = this._updateFloat3ForEffect;
  26178. this.updateFloat4 = this._updateFloat4ForEffect;
  26179. this.updateMatrix = this._updateMatrixForEffect;
  26180. this.updateVector3 = this._updateVector3ForEffect;
  26181. this.updateVector4 = this._updateVector4ForEffect;
  26182. this.updateColor3 = this._updateColor3ForEffect;
  26183. this.updateColor4 = this._updateColor4ForEffect;
  26184. }
  26185. else {
  26186. this._engine._uniformBuffers.push(this);
  26187. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26188. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26189. this.updateFloat = this._updateFloatForUniform;
  26190. this.updateFloat2 = this._updateFloat2ForUniform;
  26191. this.updateFloat3 = this._updateFloat3ForUniform;
  26192. this.updateFloat4 = this._updateFloat4ForUniform;
  26193. this.updateMatrix = this._updateMatrixForUniform;
  26194. this.updateVector3 = this._updateVector3ForUniform;
  26195. this.updateVector4 = this._updateVector4ForUniform;
  26196. this.updateColor3 = this._updateColor3ForUniform;
  26197. this.updateColor4 = this._updateColor4ForUniform;
  26198. }
  26199. }
  26200. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26201. // Properties
  26202. /**
  26203. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26204. * or just falling back on setUniformXXX calls.
  26205. */
  26206. get: function () {
  26207. return !this._noUBO;
  26208. },
  26209. enumerable: true,
  26210. configurable: true
  26211. });
  26212. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26213. /**
  26214. * Indicates if the WebGL underlying uniform buffer is in sync
  26215. * with the javascript cache data.
  26216. */
  26217. get: function () {
  26218. return !this._needSync;
  26219. },
  26220. enumerable: true,
  26221. configurable: true
  26222. });
  26223. /**
  26224. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26225. * Also, a dynamic UniformBuffer will disable cache verification and always
  26226. * update the underlying WebGL uniform buffer to the GPU.
  26227. */
  26228. UniformBuffer.prototype.isDynamic = function () {
  26229. return this._dynamic;
  26230. };
  26231. /**
  26232. * The data cache on JS side.
  26233. */
  26234. UniformBuffer.prototype.getData = function () {
  26235. return this._bufferData;
  26236. };
  26237. /**
  26238. * The underlying WebGL Uniform buffer.
  26239. */
  26240. UniformBuffer.prototype.getBuffer = function () {
  26241. return this._buffer;
  26242. };
  26243. /**
  26244. * std140 layout specifies how to align data within an UBO structure.
  26245. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26246. * for specs.
  26247. */
  26248. UniformBuffer.prototype._fillAlignment = function (size) {
  26249. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26250. // and 4x4 matrices
  26251. // TODO : change if other types are used
  26252. var alignment;
  26253. if (size <= 2) {
  26254. alignment = size;
  26255. }
  26256. else {
  26257. alignment = 4;
  26258. }
  26259. if ((this._uniformLocationPointer % alignment) !== 0) {
  26260. var oldPointer = this._uniformLocationPointer;
  26261. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26262. var diff = this._uniformLocationPointer - oldPointer;
  26263. for (var i = 0; i < diff; i++) {
  26264. this._data.push(0);
  26265. }
  26266. }
  26267. };
  26268. /**
  26269. * Adds an uniform in the buffer.
  26270. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26271. * for the layout to be correct !
  26272. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26273. * @param {number|number[]} size Data size, or data directly.
  26274. */
  26275. UniformBuffer.prototype.addUniform = function (name, size) {
  26276. if (this._noUBO) {
  26277. return;
  26278. }
  26279. if (this._uniformLocations[name] !== undefined) {
  26280. // Already existing uniform
  26281. return;
  26282. }
  26283. // This function must be called in the order of the shader layout !
  26284. // size can be the size of the uniform, or data directly
  26285. var data;
  26286. if (size instanceof Array) {
  26287. data = size;
  26288. size = data.length;
  26289. }
  26290. else {
  26291. size = size;
  26292. data = [];
  26293. // Fill with zeros
  26294. for (var i = 0; i < size; i++) {
  26295. data.push(0);
  26296. }
  26297. }
  26298. this._fillAlignment(size);
  26299. this._uniformSizes[name] = size;
  26300. this._uniformLocations[name] = this._uniformLocationPointer;
  26301. this._uniformLocationPointer += size;
  26302. for (var i = 0; i < size; i++) {
  26303. this._data.push(data[i]);
  26304. }
  26305. this._needSync = true;
  26306. };
  26307. /**
  26308. * Wrapper for addUniform.
  26309. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26310. * @param {Matrix} mat A 4x4 matrix.
  26311. */
  26312. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26313. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26314. };
  26315. /**
  26316. * Wrapper for addUniform.
  26317. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26318. * @param {number} x
  26319. * @param {number} y
  26320. */
  26321. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26322. var temp = [x, y];
  26323. this.addUniform(name, temp);
  26324. };
  26325. /**
  26326. * Wrapper for addUniform.
  26327. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26328. * @param {number} x
  26329. * @param {number} y
  26330. * @param {number} z
  26331. */
  26332. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26333. var temp = [x, y, z];
  26334. this.addUniform(name, temp);
  26335. };
  26336. /**
  26337. * Wrapper for addUniform.
  26338. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26339. * @param {Color3} color
  26340. */
  26341. UniformBuffer.prototype.addColor3 = function (name, color) {
  26342. var temp = [];
  26343. color.toArray(temp);
  26344. this.addUniform(name, temp);
  26345. };
  26346. /**
  26347. * Wrapper for addUniform.
  26348. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26349. * @param {Color3} color
  26350. * @param {number} alpha
  26351. */
  26352. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26353. var temp = [];
  26354. color.toArray(temp);
  26355. temp.push(alpha);
  26356. this.addUniform(name, temp);
  26357. };
  26358. /**
  26359. * Wrapper for addUniform.
  26360. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26361. * @param {Vector3} vector
  26362. */
  26363. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26364. var temp = [];
  26365. vector.toArray(temp);
  26366. this.addUniform(name, temp);
  26367. };
  26368. /**
  26369. * Wrapper for addUniform.
  26370. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26371. */
  26372. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26373. this.addUniform(name, 12);
  26374. };
  26375. /**
  26376. * Wrapper for addUniform.
  26377. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26378. */
  26379. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26380. this.addUniform(name, 8);
  26381. };
  26382. /**
  26383. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26384. */
  26385. UniformBuffer.prototype.create = function () {
  26386. if (this._noUBO) {
  26387. return;
  26388. }
  26389. if (this._buffer) {
  26390. return; // nothing to do
  26391. }
  26392. // See spec, alignment must be filled as a vec4
  26393. this._fillAlignment(4);
  26394. this._bufferData = new Float32Array(this._data);
  26395. this._rebuild();
  26396. this._needSync = true;
  26397. };
  26398. UniformBuffer.prototype._rebuild = function () {
  26399. if (this._noUBO) {
  26400. return;
  26401. }
  26402. if (this._dynamic) {
  26403. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26404. }
  26405. else {
  26406. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26407. }
  26408. };
  26409. /**
  26410. * Updates the WebGL Uniform Buffer on the GPU.
  26411. * If the `dynamic` flag is set to true, no cache comparison is done.
  26412. * Otherwise, the buffer will be updated only if the cache differs.
  26413. */
  26414. UniformBuffer.prototype.update = function () {
  26415. if (!this._buffer) {
  26416. this.create();
  26417. return;
  26418. }
  26419. if (!this._dynamic && !this._needSync) {
  26420. return;
  26421. }
  26422. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26423. this._needSync = false;
  26424. };
  26425. /**
  26426. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26427. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26428. * @param {number[]|Float32Array} data Flattened data
  26429. * @param {number} size Size of the data.
  26430. */
  26431. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26432. var location = this._uniformLocations[uniformName];
  26433. if (location === undefined) {
  26434. if (this._buffer) {
  26435. // Cannot add an uniform if the buffer is already created
  26436. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26437. return;
  26438. }
  26439. this.addUniform(uniformName, size);
  26440. location = this._uniformLocations[uniformName];
  26441. }
  26442. if (!this._buffer) {
  26443. this.create();
  26444. }
  26445. if (!this._dynamic) {
  26446. // Cache for static uniform buffers
  26447. var changed = false;
  26448. for (var i = 0; i < size; i++) {
  26449. if (this._bufferData[location + i] !== data[i]) {
  26450. changed = true;
  26451. this._bufferData[location + i] = data[i];
  26452. }
  26453. }
  26454. this._needSync = this._needSync || changed;
  26455. }
  26456. else {
  26457. // No cache for dynamic
  26458. for (var i = 0; i < size; i++) {
  26459. this._bufferData[location + i] = data[i];
  26460. }
  26461. }
  26462. };
  26463. // Update methods
  26464. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26465. // To match std140, matrix must be realigned
  26466. for (var i = 0; i < 3; i++) {
  26467. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26468. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26469. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26470. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26471. }
  26472. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26473. };
  26474. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26475. this._currentEffect.setMatrix3x3(name, matrix);
  26476. };
  26477. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26478. this._currentEffect.setMatrix2x2(name, matrix);
  26479. };
  26480. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26481. // To match std140, matrix must be realigned
  26482. for (var i = 0; i < 2; i++) {
  26483. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26484. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26485. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26486. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26487. }
  26488. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26489. };
  26490. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26491. this._currentEffect.setFloat(name, x);
  26492. };
  26493. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26494. UniformBuffer._tempBuffer[0] = x;
  26495. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26496. };
  26497. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26498. if (suffix === void 0) { suffix = ""; }
  26499. this._currentEffect.setFloat2(name + suffix, x, y);
  26500. };
  26501. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26502. if (suffix === void 0) { suffix = ""; }
  26503. UniformBuffer._tempBuffer[0] = x;
  26504. UniformBuffer._tempBuffer[1] = y;
  26505. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26506. };
  26507. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26508. if (suffix === void 0) { suffix = ""; }
  26509. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26510. };
  26511. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26512. if (suffix === void 0) { suffix = ""; }
  26513. UniformBuffer._tempBuffer[0] = x;
  26514. UniformBuffer._tempBuffer[1] = y;
  26515. UniformBuffer._tempBuffer[2] = z;
  26516. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26517. };
  26518. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26519. if (suffix === void 0) { suffix = ""; }
  26520. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26521. };
  26522. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26523. if (suffix === void 0) { suffix = ""; }
  26524. UniformBuffer._tempBuffer[0] = x;
  26525. UniformBuffer._tempBuffer[1] = y;
  26526. UniformBuffer._tempBuffer[2] = z;
  26527. UniformBuffer._tempBuffer[3] = w;
  26528. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26529. };
  26530. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26531. this._currentEffect.setMatrix(name, mat);
  26532. };
  26533. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26534. this.updateUniform(name, mat.toArray(), 16);
  26535. };
  26536. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26537. this._currentEffect.setVector3(name, vector);
  26538. };
  26539. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26540. vector.toArray(UniformBuffer._tempBuffer);
  26541. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26542. };
  26543. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26544. this._currentEffect.setVector4(name, vector);
  26545. };
  26546. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26547. vector.toArray(UniformBuffer._tempBuffer);
  26548. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26549. };
  26550. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26551. if (suffix === void 0) { suffix = ""; }
  26552. this._currentEffect.setColor3(name + suffix, color);
  26553. };
  26554. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26555. if (suffix === void 0) { suffix = ""; }
  26556. color.toArray(UniformBuffer._tempBuffer);
  26557. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26558. };
  26559. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26560. if (suffix === void 0) { suffix = ""; }
  26561. this._currentEffect.setColor4(name + suffix, color, alpha);
  26562. };
  26563. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26564. if (suffix === void 0) { suffix = ""; }
  26565. color.toArray(UniformBuffer._tempBuffer);
  26566. UniformBuffer._tempBuffer[3] = alpha;
  26567. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26568. };
  26569. /**
  26570. * Sets a sampler uniform on the effect.
  26571. * @param {string} name Name of the sampler.
  26572. * @param {Texture} texture
  26573. */
  26574. UniformBuffer.prototype.setTexture = function (name, texture) {
  26575. this._currentEffect.setTexture(name, texture);
  26576. };
  26577. /**
  26578. * Directly updates the value of the uniform in the cache AND on the GPU.
  26579. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26580. * @param {number[]|Float32Array} data Flattened data
  26581. */
  26582. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26583. this.updateUniform(uniformName, data, data.length);
  26584. this.update();
  26585. };
  26586. /**
  26587. * Binds this uniform buffer to an effect.
  26588. * @param {Effect} effect
  26589. * @param {string} name Name of the uniform block in the shader.
  26590. */
  26591. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26592. this._currentEffect = effect;
  26593. if (this._noUBO) {
  26594. return;
  26595. }
  26596. effect.bindUniformBuffer(this._buffer, name);
  26597. };
  26598. /**
  26599. * Disposes the uniform buffer.
  26600. */
  26601. UniformBuffer.prototype.dispose = function () {
  26602. if (this._noUBO) {
  26603. return;
  26604. }
  26605. var index = this._engine._uniformBuffers.indexOf(this);
  26606. if (index !== -1) {
  26607. this._engine._uniformBuffers.splice(index, 1);
  26608. }
  26609. if (!this._buffer) {
  26610. return;
  26611. }
  26612. if (this._engine._releaseBuffer(this._buffer)) {
  26613. this._buffer = null;
  26614. }
  26615. };
  26616. // Pool for avoiding memory leaks
  26617. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26618. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26619. return UniformBuffer;
  26620. }());
  26621. BABYLON.UniformBuffer = UniformBuffer;
  26622. })(BABYLON || (BABYLON = {}));
  26623. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26624. var BABYLON;
  26625. (function (BABYLON) {
  26626. var PushMaterial = (function (_super) {
  26627. __extends(PushMaterial, _super);
  26628. function PushMaterial(name, scene) {
  26629. var _this = _super.call(this, name, scene) || this;
  26630. _this.storeEffectOnSubMeshes = true;
  26631. return _this;
  26632. }
  26633. PushMaterial.prototype.getEffect = function () {
  26634. return this._activeEffect;
  26635. };
  26636. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26637. if (!mesh) {
  26638. return false;
  26639. }
  26640. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26641. return true;
  26642. }
  26643. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26644. };
  26645. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26646. this._activeEffect.setMatrix("world", world);
  26647. };
  26648. PushMaterial.prototype.bind = function (world, mesh) {
  26649. if (!mesh) {
  26650. return;
  26651. }
  26652. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26653. };
  26654. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26655. _super.prototype._afterBind.call(this, mesh);
  26656. this.getScene()._cachedEffect = effect;
  26657. };
  26658. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26659. if (visibility === void 0) { visibility = 1; }
  26660. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26661. };
  26662. return PushMaterial;
  26663. }(BABYLON.Material));
  26664. BABYLON.PushMaterial = PushMaterial;
  26665. })(BABYLON || (BABYLON = {}));
  26666. //# sourceMappingURL=babylon.pushMaterial.js.map
  26667. var BABYLON;
  26668. (function (BABYLON) {
  26669. var VertexData = (function () {
  26670. function VertexData() {
  26671. }
  26672. VertexData.prototype.set = function (data, kind) {
  26673. switch (kind) {
  26674. case BABYLON.VertexBuffer.PositionKind:
  26675. this.positions = data;
  26676. break;
  26677. case BABYLON.VertexBuffer.NormalKind:
  26678. this.normals = data;
  26679. break;
  26680. case BABYLON.VertexBuffer.TangentKind:
  26681. this.tangents = data;
  26682. break;
  26683. case BABYLON.VertexBuffer.UVKind:
  26684. this.uvs = data;
  26685. break;
  26686. case BABYLON.VertexBuffer.UV2Kind:
  26687. this.uvs2 = data;
  26688. break;
  26689. case BABYLON.VertexBuffer.UV3Kind:
  26690. this.uvs3 = data;
  26691. break;
  26692. case BABYLON.VertexBuffer.UV4Kind:
  26693. this.uvs4 = data;
  26694. break;
  26695. case BABYLON.VertexBuffer.UV5Kind:
  26696. this.uvs5 = data;
  26697. break;
  26698. case BABYLON.VertexBuffer.UV6Kind:
  26699. this.uvs6 = data;
  26700. break;
  26701. case BABYLON.VertexBuffer.ColorKind:
  26702. this.colors = data;
  26703. break;
  26704. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26705. this.matricesIndices = data;
  26706. break;
  26707. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26708. this.matricesWeights = data;
  26709. break;
  26710. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26711. this.matricesIndicesExtra = data;
  26712. break;
  26713. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26714. this.matricesWeightsExtra = data;
  26715. break;
  26716. }
  26717. };
  26718. /**
  26719. * Associates the vertexData to the passed Mesh.
  26720. * Sets it as updatable or not (default `false`).
  26721. * Returns the VertexData.
  26722. */
  26723. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26724. this._applyTo(mesh, updatable);
  26725. return this;
  26726. };
  26727. /**
  26728. * Associates the vertexData to the passed Geometry.
  26729. * Sets it as updatable or not (default `false`).
  26730. * Returns the VertexData.
  26731. */
  26732. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26733. this._applyTo(geometry, updatable);
  26734. return this;
  26735. };
  26736. /**
  26737. * Updates the associated mesh.
  26738. * Returns the VertexData.
  26739. */
  26740. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26741. this._update(mesh);
  26742. return this;
  26743. };
  26744. /**
  26745. * Updates the associated geometry.
  26746. * Returns the VertexData.
  26747. */
  26748. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26749. this._update(geometry);
  26750. return this;
  26751. };
  26752. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26753. if (this.positions) {
  26754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26755. }
  26756. if (this.normals) {
  26757. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26758. }
  26759. if (this.tangents) {
  26760. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26761. }
  26762. if (this.uvs) {
  26763. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26764. }
  26765. if (this.uvs2) {
  26766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26767. }
  26768. if (this.uvs3) {
  26769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26770. }
  26771. if (this.uvs4) {
  26772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26773. }
  26774. if (this.uvs5) {
  26775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26776. }
  26777. if (this.uvs6) {
  26778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26779. }
  26780. if (this.colors) {
  26781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26782. }
  26783. if (this.matricesIndices) {
  26784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26785. }
  26786. if (this.matricesWeights) {
  26787. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26788. }
  26789. if (this.matricesIndicesExtra) {
  26790. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26791. }
  26792. if (this.matricesWeightsExtra) {
  26793. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26794. }
  26795. if (this.indices) {
  26796. meshOrGeometry.setIndices(this.indices);
  26797. }
  26798. return this;
  26799. };
  26800. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26801. if (this.positions) {
  26802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26803. }
  26804. if (this.normals) {
  26805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26806. }
  26807. if (this.tangents) {
  26808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26809. }
  26810. if (this.uvs) {
  26811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26812. }
  26813. if (this.uvs2) {
  26814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26815. }
  26816. if (this.uvs3) {
  26817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26818. }
  26819. if (this.uvs4) {
  26820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26821. }
  26822. if (this.uvs5) {
  26823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26824. }
  26825. if (this.uvs6) {
  26826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26827. }
  26828. if (this.colors) {
  26829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26830. }
  26831. if (this.matricesIndices) {
  26832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26833. }
  26834. if (this.matricesWeights) {
  26835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26836. }
  26837. if (this.matricesIndicesExtra) {
  26838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26839. }
  26840. if (this.matricesWeightsExtra) {
  26841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26842. }
  26843. if (this.indices) {
  26844. meshOrGeometry.setIndices(this.indices);
  26845. }
  26846. return this;
  26847. };
  26848. /**
  26849. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26850. * Returns the VertexData.
  26851. */
  26852. VertexData.prototype.transform = function (matrix) {
  26853. var transformed = BABYLON.Vector3.Zero();
  26854. var index;
  26855. if (this.positions) {
  26856. var position = BABYLON.Vector3.Zero();
  26857. for (index = 0; index < this.positions.length; index += 3) {
  26858. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26859. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26860. this.positions[index] = transformed.x;
  26861. this.positions[index + 1] = transformed.y;
  26862. this.positions[index + 2] = transformed.z;
  26863. }
  26864. }
  26865. if (this.normals) {
  26866. var normal = BABYLON.Vector3.Zero();
  26867. for (index = 0; index < this.normals.length; index += 3) {
  26868. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26869. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26870. this.normals[index] = transformed.x;
  26871. this.normals[index + 1] = transformed.y;
  26872. this.normals[index + 2] = transformed.z;
  26873. }
  26874. }
  26875. if (this.tangents) {
  26876. var tangent = BABYLON.Vector4.Zero();
  26877. var tangentTransformed = BABYLON.Vector4.Zero();
  26878. for (index = 0; index < this.tangents.length; index += 4) {
  26879. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26880. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26881. this.tangents[index] = tangentTransformed.x;
  26882. this.tangents[index + 1] = tangentTransformed.y;
  26883. this.tangents[index + 2] = tangentTransformed.z;
  26884. this.tangents[index + 3] = tangentTransformed.w;
  26885. }
  26886. }
  26887. return this;
  26888. };
  26889. /**
  26890. * Merges the passed VertexData into the current one.
  26891. * Returns the modified VertexData.
  26892. */
  26893. VertexData.prototype.merge = function (other) {
  26894. if (other.indices) {
  26895. if (!this.indices) {
  26896. this.indices = [];
  26897. }
  26898. var offset = this.positions ? this.positions.length / 3 : 0;
  26899. for (var index = 0; index < other.indices.length; index++) {
  26900. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26901. this.indices.push(other.indices[index] + offset);
  26902. }
  26903. }
  26904. this.positions = this._mergeElement(this.positions, other.positions);
  26905. this.normals = this._mergeElement(this.normals, other.normals);
  26906. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26907. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26908. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26909. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26910. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26911. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26912. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26913. this.colors = this._mergeElement(this.colors, other.colors);
  26914. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26915. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26916. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26917. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26918. return this;
  26919. };
  26920. VertexData.prototype._mergeElement = function (source, other) {
  26921. if (!other)
  26922. return source;
  26923. if (!source)
  26924. return other;
  26925. var len = other.length + source.length;
  26926. var isSrcTypedArray = source instanceof Float32Array;
  26927. var isOthTypedArray = other instanceof Float32Array;
  26928. // use non-loop method when the source is Float32Array
  26929. if (isSrcTypedArray) {
  26930. var ret32 = new Float32Array(len);
  26931. ret32.set(source);
  26932. ret32.set(other, source.length);
  26933. return ret32;
  26934. // source is number[], when other is also use concat
  26935. }
  26936. else if (!isOthTypedArray) {
  26937. return source.concat(other);
  26938. // source is a number[], but other is a Float32Array, loop required
  26939. }
  26940. else {
  26941. var ret = source.slice(0); // copy source to a separate array
  26942. for (var i = 0, len = other.length; i < len; i++) {
  26943. ret.push(other[i]);
  26944. }
  26945. return ret;
  26946. }
  26947. };
  26948. /**
  26949. * Serializes the VertexData.
  26950. * Returns a serialized object.
  26951. */
  26952. VertexData.prototype.serialize = function () {
  26953. var serializationObject = this.serialize();
  26954. if (this.positions) {
  26955. serializationObject.positions = this.positions;
  26956. }
  26957. if (this.normals) {
  26958. serializationObject.normals = this.normals;
  26959. }
  26960. if (this.tangents) {
  26961. serializationObject.tangents = this.tangents;
  26962. }
  26963. if (this.uvs) {
  26964. serializationObject.uvs = this.uvs;
  26965. }
  26966. if (this.uvs2) {
  26967. serializationObject.uvs2 = this.uvs2;
  26968. }
  26969. if (this.uvs3) {
  26970. serializationObject.uvs3 = this.uvs3;
  26971. }
  26972. if (this.uvs4) {
  26973. serializationObject.uvs4 = this.uvs4;
  26974. }
  26975. if (this.uvs5) {
  26976. serializationObject.uvs5 = this.uvs5;
  26977. }
  26978. if (this.uvs6) {
  26979. serializationObject.uvs6 = this.uvs6;
  26980. }
  26981. if (this.colors) {
  26982. serializationObject.colors = this.colors;
  26983. }
  26984. if (this.matricesIndices) {
  26985. serializationObject.matricesIndices = this.matricesIndices;
  26986. serializationObject.matricesIndices._isExpanded = true;
  26987. }
  26988. if (this.matricesWeights) {
  26989. serializationObject.matricesWeights = this.matricesWeights;
  26990. }
  26991. if (this.matricesIndicesExtra) {
  26992. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26993. serializationObject.matricesIndicesExtra._isExpanded = true;
  26994. }
  26995. if (this.matricesWeightsExtra) {
  26996. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26997. }
  26998. serializationObject.indices = this.indices;
  26999. return serializationObject;
  27000. };
  27001. // Statics
  27002. /**
  27003. * Returns the object VertexData associated to the passed mesh.
  27004. */
  27005. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27006. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27007. };
  27008. /**
  27009. * Returns the object VertexData associated to the passed geometry.
  27010. */
  27011. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27012. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27013. };
  27014. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27015. var result = new VertexData();
  27016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27017. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27018. }
  27019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27020. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27021. }
  27022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27023. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27024. }
  27025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27026. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27027. }
  27028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27029. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27030. }
  27031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27032. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27033. }
  27034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27035. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27036. }
  27037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27038. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27039. }
  27040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27041. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27042. }
  27043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27044. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27045. }
  27046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27047. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27048. }
  27049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27050. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27051. }
  27052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27053. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27054. }
  27055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27056. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27057. }
  27058. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27059. return result;
  27060. };
  27061. /**
  27062. * Creates the vertexData of the Ribbon.
  27063. */
  27064. VertexData.CreateRibbon = function (options) {
  27065. var pathArray = options.pathArray;
  27066. var closeArray = options.closeArray || false;
  27067. var closePath = options.closePath || false;
  27068. var invertUV = options.invertUV || false;
  27069. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27070. var offset = options.offset || defaultOffset;
  27071. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27072. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27073. var customUV = options.uvs;
  27074. var customColors = options.colors;
  27075. var positions = [];
  27076. var indices = [];
  27077. var normals = [];
  27078. var uvs = [];
  27079. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27080. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27081. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27082. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27083. var minlg; // minimal length among all paths from pathArray
  27084. var lg = []; // array of path lengths : nb of vertex per path
  27085. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27086. var p; // path iterator
  27087. var i; // point iterator
  27088. var j; // point iterator
  27089. // if single path in pathArray
  27090. if (pathArray.length < 2) {
  27091. var ar1 = [];
  27092. var ar2 = [];
  27093. for (i = 0; i < pathArray[0].length - offset; i++) {
  27094. ar1.push(pathArray[0][i]);
  27095. ar2.push(pathArray[0][i + offset]);
  27096. }
  27097. pathArray = [ar1, ar2];
  27098. }
  27099. // positions and horizontal distances (u)
  27100. var idc = 0;
  27101. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27102. var path;
  27103. var l;
  27104. minlg = pathArray[0].length;
  27105. var vectlg;
  27106. var dist;
  27107. for (p = 0; p < pathArray.length; p++) {
  27108. uTotalDistance[p] = 0;
  27109. us[p] = [0];
  27110. path = pathArray[p];
  27111. l = path.length;
  27112. minlg = (minlg < l) ? minlg : l;
  27113. j = 0;
  27114. while (j < l) {
  27115. positions.push(path[j].x, path[j].y, path[j].z);
  27116. if (j > 0) {
  27117. vectlg = path[j].subtract(path[j - 1]).length();
  27118. dist = vectlg + uTotalDistance[p];
  27119. us[p].push(dist);
  27120. uTotalDistance[p] = dist;
  27121. }
  27122. j++;
  27123. }
  27124. if (closePath) {
  27125. j--;
  27126. positions.push(path[0].x, path[0].y, path[0].z);
  27127. vectlg = path[j].subtract(path[0]).length();
  27128. dist = vectlg + uTotalDistance[p];
  27129. us[p].push(dist);
  27130. uTotalDistance[p] = dist;
  27131. }
  27132. lg[p] = l + closePathCorr;
  27133. idx[p] = idc;
  27134. idc += (l + closePathCorr);
  27135. }
  27136. // vertical distances (v)
  27137. var path1;
  27138. var path2;
  27139. var vertex1;
  27140. var vertex2;
  27141. for (i = 0; i < minlg + closePathCorr; i++) {
  27142. vTotalDistance[i] = 0;
  27143. vs[i] = [0];
  27144. for (p = 0; p < pathArray.length - 1; p++) {
  27145. path1 = pathArray[p];
  27146. path2 = pathArray[p + 1];
  27147. if (i === minlg) {
  27148. vertex1 = path1[0];
  27149. vertex2 = path2[0];
  27150. }
  27151. else {
  27152. vertex1 = path1[i];
  27153. vertex2 = path2[i];
  27154. }
  27155. vectlg = vertex2.subtract(vertex1).length();
  27156. dist = vectlg + vTotalDistance[i];
  27157. vs[i].push(dist);
  27158. vTotalDistance[i] = dist;
  27159. }
  27160. if (closeArray) {
  27161. path1 = pathArray[p];
  27162. path2 = pathArray[0];
  27163. if (i === minlg) {
  27164. vertex2 = path2[0];
  27165. }
  27166. vectlg = vertex2.subtract(vertex1).length();
  27167. dist = vectlg + vTotalDistance[i];
  27168. vTotalDistance[i] = dist;
  27169. }
  27170. }
  27171. // uvs
  27172. var u;
  27173. var v;
  27174. if (customUV) {
  27175. for (p = 0; p < customUV.length; p++) {
  27176. uvs.push(customUV[p].x, customUV[p].y);
  27177. }
  27178. }
  27179. else {
  27180. for (p = 0; p < pathArray.length; p++) {
  27181. for (i = 0; i < minlg + closePathCorr; i++) {
  27182. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27183. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27184. if (invertUV) {
  27185. uvs.push(v, u);
  27186. }
  27187. else {
  27188. uvs.push(u, v);
  27189. }
  27190. }
  27191. }
  27192. }
  27193. // indices
  27194. p = 0; // path index
  27195. var pi = 0; // positions array index
  27196. var l1 = lg[p] - 1; // path1 length
  27197. var l2 = lg[p + 1] - 1; // path2 length
  27198. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27199. var shft = idx[1] - idx[0]; // shift
  27200. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27201. while (pi <= min && p < path1nb) {
  27202. // 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
  27203. indices.push(pi, pi + shft, pi + 1);
  27204. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27205. pi += 1;
  27206. if (pi === min) {
  27207. p++;
  27208. if (p === lg.length - 1) {
  27209. shft = idx[0] - idx[p];
  27210. l1 = lg[p] - 1;
  27211. l2 = lg[0] - 1;
  27212. }
  27213. else {
  27214. shft = idx[p + 1] - idx[p];
  27215. l1 = lg[p] - 1;
  27216. l2 = lg[p + 1] - 1;
  27217. }
  27218. pi = idx[p];
  27219. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27220. }
  27221. }
  27222. // normals
  27223. VertexData.ComputeNormals(positions, indices, normals);
  27224. if (closePath) {
  27225. var indexFirst = 0;
  27226. var indexLast = 0;
  27227. for (p = 0; p < pathArray.length; p++) {
  27228. indexFirst = idx[p] * 3;
  27229. if (p + 1 < pathArray.length) {
  27230. indexLast = (idx[p + 1] - 1) * 3;
  27231. }
  27232. else {
  27233. indexLast = normals.length - 3;
  27234. }
  27235. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27236. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27237. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27238. normals[indexLast] = normals[indexFirst];
  27239. normals[indexLast + 1] = normals[indexFirst + 1];
  27240. normals[indexLast + 2] = normals[indexFirst + 2];
  27241. }
  27242. }
  27243. // sides
  27244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27245. // Colors
  27246. if (customColors) {
  27247. var colors = new Float32Array(customColors.length * 4);
  27248. for (var c = 0; c < customColors.length; c++) {
  27249. colors[c * 4] = customColors[c].r;
  27250. colors[c * 4 + 1] = customColors[c].g;
  27251. colors[c * 4 + 2] = customColors[c].b;
  27252. colors[c * 4 + 3] = customColors[c].a;
  27253. }
  27254. }
  27255. // Result
  27256. var vertexData = new VertexData();
  27257. var positions32 = new Float32Array(positions);
  27258. var normals32 = new Float32Array(normals);
  27259. var uvs32 = new Float32Array(uvs);
  27260. vertexData.indices = indices;
  27261. vertexData.positions = positions32;
  27262. vertexData.normals = normals32;
  27263. vertexData.uvs = uvs32;
  27264. if (customColors) {
  27265. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27266. }
  27267. if (closePath) {
  27268. vertexData._idx = idx;
  27269. }
  27270. return vertexData;
  27271. };
  27272. /**
  27273. * Creates the VertexData of the Box.
  27274. */
  27275. VertexData.CreateBox = function (options) {
  27276. var normalsSource = [
  27277. new BABYLON.Vector3(0, 0, 1),
  27278. new BABYLON.Vector3(0, 0, -1),
  27279. new BABYLON.Vector3(1, 0, 0),
  27280. new BABYLON.Vector3(-1, 0, 0),
  27281. new BABYLON.Vector3(0, 1, 0),
  27282. new BABYLON.Vector3(0, -1, 0)
  27283. ];
  27284. var indices = [];
  27285. var positions = [];
  27286. var normals = [];
  27287. var uvs = [];
  27288. var width = options.width || options.size || 1;
  27289. var height = options.height || options.size || 1;
  27290. var depth = options.depth || options.size || 1;
  27291. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27292. var faceUV = options.faceUV || new Array(6);
  27293. var faceColors = options.faceColors;
  27294. var colors = [];
  27295. // default face colors and UV if undefined
  27296. for (var f = 0; f < 6; f++) {
  27297. if (faceUV[f] === undefined) {
  27298. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27299. }
  27300. if (faceColors && faceColors[f] === undefined) {
  27301. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27302. }
  27303. }
  27304. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27305. // Create each face in turn.
  27306. for (var index = 0; index < normalsSource.length; index++) {
  27307. var normal = normalsSource[index];
  27308. // Get two vectors perpendicular to the face normal and to each other.
  27309. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27310. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27311. // Six indices (two triangles) per face.
  27312. var verticesLength = positions.length / 3;
  27313. indices.push(verticesLength);
  27314. indices.push(verticesLength + 1);
  27315. indices.push(verticesLength + 2);
  27316. indices.push(verticesLength);
  27317. indices.push(verticesLength + 2);
  27318. indices.push(verticesLength + 3);
  27319. // Four vertices per face.
  27320. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27321. positions.push(vertex.x, vertex.y, vertex.z);
  27322. normals.push(normal.x, normal.y, normal.z);
  27323. uvs.push(faceUV[index].z, faceUV[index].w);
  27324. if (faceColors) {
  27325. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27326. }
  27327. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27328. positions.push(vertex.x, vertex.y, vertex.z);
  27329. normals.push(normal.x, normal.y, normal.z);
  27330. uvs.push(faceUV[index].x, faceUV[index].w);
  27331. if (faceColors) {
  27332. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27333. }
  27334. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27335. positions.push(vertex.x, vertex.y, vertex.z);
  27336. normals.push(normal.x, normal.y, normal.z);
  27337. uvs.push(faceUV[index].x, faceUV[index].y);
  27338. if (faceColors) {
  27339. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27340. }
  27341. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27342. positions.push(vertex.x, vertex.y, vertex.z);
  27343. normals.push(normal.x, normal.y, normal.z);
  27344. uvs.push(faceUV[index].z, faceUV[index].y);
  27345. if (faceColors) {
  27346. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27347. }
  27348. }
  27349. // sides
  27350. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27351. // Result
  27352. var vertexData = new VertexData();
  27353. vertexData.indices = indices;
  27354. vertexData.positions = positions;
  27355. vertexData.normals = normals;
  27356. vertexData.uvs = uvs;
  27357. if (faceColors) {
  27358. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27359. vertexData.colors = totalColors;
  27360. }
  27361. return vertexData;
  27362. };
  27363. /**
  27364. * Creates the VertexData of the Sphere.
  27365. */
  27366. VertexData.CreateSphere = function (options) {
  27367. var segments = options.segments || 32;
  27368. var diameterX = options.diameterX || options.diameter || 1;
  27369. var diameterY = options.diameterY || options.diameter || 1;
  27370. var diameterZ = options.diameterZ || options.diameter || 1;
  27371. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27372. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27373. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27374. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27375. var totalZRotationSteps = 2 + segments;
  27376. var totalYRotationSteps = 2 * totalZRotationSteps;
  27377. var indices = [];
  27378. var positions = [];
  27379. var normals = [];
  27380. var uvs = [];
  27381. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27382. var normalizedZ = zRotationStep / totalZRotationSteps;
  27383. var angleZ = normalizedZ * Math.PI * slice;
  27384. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27385. var normalizedY = yRotationStep / totalYRotationSteps;
  27386. var angleY = normalizedY * Math.PI * 2 * arc;
  27387. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27388. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27389. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27390. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27391. var vertex = complete.multiply(radius);
  27392. var normal = complete.divide(radius).normalize();
  27393. positions.push(vertex.x, vertex.y, vertex.z);
  27394. normals.push(normal.x, normal.y, normal.z);
  27395. uvs.push(normalizedY, normalizedZ);
  27396. }
  27397. if (zRotationStep > 0) {
  27398. var verticesCount = positions.length / 3;
  27399. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27400. indices.push((firstIndex));
  27401. indices.push((firstIndex + 1));
  27402. indices.push(firstIndex + totalYRotationSteps + 1);
  27403. indices.push((firstIndex + totalYRotationSteps + 1));
  27404. indices.push((firstIndex + 1));
  27405. indices.push((firstIndex + totalYRotationSteps + 2));
  27406. }
  27407. }
  27408. }
  27409. // Sides
  27410. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27411. // Result
  27412. var vertexData = new VertexData();
  27413. vertexData.indices = indices;
  27414. vertexData.positions = positions;
  27415. vertexData.normals = normals;
  27416. vertexData.uvs = uvs;
  27417. return vertexData;
  27418. };
  27419. /**
  27420. * Creates the VertexData of the Cylinder or Cone.
  27421. */
  27422. VertexData.CreateCylinder = function (options) {
  27423. var height = options.height || 2;
  27424. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27425. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27426. var tessellation = options.tessellation || 24;
  27427. var subdivisions = options.subdivisions || 1;
  27428. var hasRings = options.hasRings;
  27429. var enclose = options.enclose;
  27430. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27431. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27432. var faceUV = options.faceUV || new Array(3);
  27433. var faceColors = options.faceColors;
  27434. // default face colors and UV if undefined
  27435. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27436. var ringNb = (hasRings) ? subdivisions : 1;
  27437. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27438. var f;
  27439. for (f = 0; f < surfaceNb; f++) {
  27440. if (faceColors && faceColors[f] === undefined) {
  27441. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27442. }
  27443. }
  27444. for (f = 0; f < surfaceNb; f++) {
  27445. if (faceUV && faceUV[f] === undefined) {
  27446. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27447. }
  27448. }
  27449. var indices = [];
  27450. var positions = [];
  27451. var normals = [];
  27452. var uvs = [];
  27453. var colors = [];
  27454. var angle_step = Math.PI * 2 * arc / tessellation;
  27455. var angle;
  27456. var h;
  27457. var radius;
  27458. var tan = (diameterBottom - diameterTop) / 2 / height;
  27459. var ringVertex = BABYLON.Vector3.Zero();
  27460. var ringNormal = BABYLON.Vector3.Zero();
  27461. var ringFirstVertex = BABYLON.Vector3.Zero();
  27462. var ringFirstNormal = BABYLON.Vector3.Zero();
  27463. var quadNormal = BABYLON.Vector3.Zero();
  27464. var Y = BABYLON.Axis.Y;
  27465. // positions, normals, uvs
  27466. var i;
  27467. var j;
  27468. var r;
  27469. var ringIdx = 1;
  27470. var s = 1; // surface index
  27471. var cs = 0;
  27472. var v = 0;
  27473. for (i = 0; i <= subdivisions; i++) {
  27474. h = i / subdivisions;
  27475. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27476. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27477. for (r = 0; r < ringIdx; r++) {
  27478. if (hasRings) {
  27479. s += r;
  27480. }
  27481. if (enclose) {
  27482. s += 2 * r;
  27483. }
  27484. for (j = 0; j <= tessellation; j++) {
  27485. angle = j * angle_step;
  27486. // position
  27487. ringVertex.x = Math.cos(-angle) * radius;
  27488. ringVertex.y = -height / 2 + h * height;
  27489. ringVertex.z = Math.sin(-angle) * radius;
  27490. // normal
  27491. if (diameterTop === 0 && i === subdivisions) {
  27492. // if no top cap, reuse former normals
  27493. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27494. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27495. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27496. }
  27497. else {
  27498. ringNormal.x = ringVertex.x;
  27499. ringNormal.z = ringVertex.z;
  27500. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27501. ringNormal.normalize();
  27502. }
  27503. // keep first ring vertex values for enclose
  27504. if (j === 0) {
  27505. ringFirstVertex.copyFrom(ringVertex);
  27506. ringFirstNormal.copyFrom(ringNormal);
  27507. }
  27508. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27509. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27510. if (hasRings) {
  27511. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27512. }
  27513. else {
  27514. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27515. }
  27516. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27517. if (faceColors) {
  27518. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27519. }
  27520. }
  27521. // if enclose, add four vertices and their dedicated normals
  27522. if (arc !== 1 && enclose) {
  27523. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27524. positions.push(0, ringVertex.y, 0);
  27525. positions.push(0, ringVertex.y, 0);
  27526. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27527. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27528. quadNormal.normalize();
  27529. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27530. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27531. quadNormal.normalize();
  27532. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27533. if (hasRings) {
  27534. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27535. }
  27536. else {
  27537. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27538. }
  27539. uvs.push(faceUV[s + 1].x, v);
  27540. uvs.push(faceUV[s + 1].z, v);
  27541. if (hasRings) {
  27542. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27543. }
  27544. else {
  27545. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27546. }
  27547. uvs.push(faceUV[s + 2].x, v);
  27548. uvs.push(faceUV[s + 2].z, v);
  27549. if (faceColors) {
  27550. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27551. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27552. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27553. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27554. }
  27555. }
  27556. if (cs !== s) {
  27557. cs = s;
  27558. }
  27559. }
  27560. }
  27561. // indices
  27562. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27563. var s;
  27564. i = 0;
  27565. for (s = 0; s < subdivisions; s++) {
  27566. for (j = 0; j < tessellation; j++) {
  27567. var i0 = i * (e + 1) + j;
  27568. var i1 = (i + 1) * (e + 1) + j;
  27569. var i2 = i * (e + 1) + (j + 1);
  27570. var i3 = (i + 1) * (e + 1) + (j + 1);
  27571. indices.push(i0, i1, i2);
  27572. indices.push(i3, i2, i1);
  27573. }
  27574. if (arc !== 1 && enclose) {
  27575. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27576. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27577. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27578. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27579. }
  27580. i = (hasRings) ? (i + 2) : (i + 1);
  27581. }
  27582. // Caps
  27583. var createCylinderCap = function (isTop) {
  27584. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27585. if (radius === 0) {
  27586. return;
  27587. }
  27588. // Cap positions, normals & uvs
  27589. var angle;
  27590. var circleVector;
  27591. var i;
  27592. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27593. var c;
  27594. if (faceColors) {
  27595. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27596. }
  27597. // cap center
  27598. var vbase = positions.length / 3;
  27599. var offset = isTop ? height / 2 : -height / 2;
  27600. var center = new BABYLON.Vector3(0, offset, 0);
  27601. positions.push(center.x, center.y, center.z);
  27602. normals.push(0, isTop ? 1 : -1, 0);
  27603. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27604. if (faceColors) {
  27605. colors.push(c.r, c.g, c.b, c.a);
  27606. }
  27607. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27608. for (i = 0; i <= tessellation; i++) {
  27609. angle = Math.PI * 2 * i * arc / tessellation;
  27610. var cos = Math.cos(-angle);
  27611. var sin = Math.sin(-angle);
  27612. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27613. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27614. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27615. normals.push(0, isTop ? 1 : -1, 0);
  27616. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27617. if (faceColors) {
  27618. colors.push(c.r, c.g, c.b, c.a);
  27619. }
  27620. }
  27621. // Cap indices
  27622. for (i = 0; i < tessellation; i++) {
  27623. if (!isTop) {
  27624. indices.push(vbase);
  27625. indices.push(vbase + (i + 1));
  27626. indices.push(vbase + (i + 2));
  27627. }
  27628. else {
  27629. indices.push(vbase);
  27630. indices.push(vbase + (i + 2));
  27631. indices.push(vbase + (i + 1));
  27632. }
  27633. }
  27634. };
  27635. // add caps to geometry
  27636. createCylinderCap(false);
  27637. createCylinderCap(true);
  27638. // Sides
  27639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27640. var vertexData = new VertexData();
  27641. vertexData.indices = indices;
  27642. vertexData.positions = positions;
  27643. vertexData.normals = normals;
  27644. vertexData.uvs = uvs;
  27645. if (faceColors) {
  27646. vertexData.colors = colors;
  27647. }
  27648. return vertexData;
  27649. };
  27650. /**
  27651. * Creates the VertexData of the Torus.
  27652. */
  27653. VertexData.CreateTorus = function (options) {
  27654. var indices = [];
  27655. var positions = [];
  27656. var normals = [];
  27657. var uvs = [];
  27658. var diameter = options.diameter || 1;
  27659. var thickness = options.thickness || 0.5;
  27660. var tessellation = options.tessellation || 16;
  27661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27662. var stride = tessellation + 1;
  27663. for (var i = 0; i <= tessellation; i++) {
  27664. var u = i / tessellation;
  27665. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27666. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27667. for (var j = 0; j <= tessellation; j++) {
  27668. var v = 1 - j / tessellation;
  27669. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27670. var dx = Math.cos(innerAngle);
  27671. var dy = Math.sin(innerAngle);
  27672. // Create a vertex.
  27673. var normal = new BABYLON.Vector3(dx, dy, 0);
  27674. var position = normal.scale(thickness / 2);
  27675. var textureCoordinate = new BABYLON.Vector2(u, v);
  27676. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27677. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27678. positions.push(position.x, position.y, position.z);
  27679. normals.push(normal.x, normal.y, normal.z);
  27680. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27681. // And create indices for two triangles.
  27682. var nextI = (i + 1) % stride;
  27683. var nextJ = (j + 1) % stride;
  27684. indices.push(i * stride + j);
  27685. indices.push(i * stride + nextJ);
  27686. indices.push(nextI * stride + j);
  27687. indices.push(i * stride + nextJ);
  27688. indices.push(nextI * stride + nextJ);
  27689. indices.push(nextI * stride + j);
  27690. }
  27691. }
  27692. // Sides
  27693. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27694. // Result
  27695. var vertexData = new VertexData();
  27696. vertexData.indices = indices;
  27697. vertexData.positions = positions;
  27698. vertexData.normals = normals;
  27699. vertexData.uvs = uvs;
  27700. return vertexData;
  27701. };
  27702. /**
  27703. * Creates the VertexData of the LineSystem.
  27704. */
  27705. VertexData.CreateLineSystem = function (options) {
  27706. var indices = [];
  27707. var positions = [];
  27708. var lines = options.lines;
  27709. var idx = 0;
  27710. for (var l = 0; l < lines.length; l++) {
  27711. var points = lines[l];
  27712. for (var index = 0; index < points.length; index++) {
  27713. positions.push(points[index].x, points[index].y, points[index].z);
  27714. if (index > 0) {
  27715. indices.push(idx - 1);
  27716. indices.push(idx);
  27717. }
  27718. idx++;
  27719. }
  27720. }
  27721. var vertexData = new VertexData();
  27722. vertexData.indices = indices;
  27723. vertexData.positions = positions;
  27724. return vertexData;
  27725. };
  27726. /**
  27727. * Create the VertexData of the DashedLines.
  27728. */
  27729. VertexData.CreateDashedLines = function (options) {
  27730. var dashSize = options.dashSize || 3;
  27731. var gapSize = options.gapSize || 1;
  27732. var dashNb = options.dashNb || 200;
  27733. var points = options.points;
  27734. var positions = new Array();
  27735. var indices = new Array();
  27736. var curvect = BABYLON.Vector3.Zero();
  27737. var lg = 0;
  27738. var nb = 0;
  27739. var shft = 0;
  27740. var dashshft = 0;
  27741. var curshft = 0;
  27742. var idx = 0;
  27743. var i = 0;
  27744. for (i = 0; i < points.length - 1; i++) {
  27745. points[i + 1].subtractToRef(points[i], curvect);
  27746. lg += curvect.length();
  27747. }
  27748. shft = lg / dashNb;
  27749. dashshft = dashSize * shft / (dashSize + gapSize);
  27750. for (i = 0; i < points.length - 1; i++) {
  27751. points[i + 1].subtractToRef(points[i], curvect);
  27752. nb = Math.floor(curvect.length() / shft);
  27753. curvect.normalize();
  27754. for (var j = 0; j < nb; j++) {
  27755. curshft = shft * j;
  27756. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27757. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27758. indices.push(idx, idx + 1);
  27759. idx += 2;
  27760. }
  27761. }
  27762. // Result
  27763. var vertexData = new VertexData();
  27764. vertexData.positions = positions;
  27765. vertexData.indices = indices;
  27766. return vertexData;
  27767. };
  27768. /**
  27769. * Creates the VertexData of the Ground.
  27770. */
  27771. VertexData.CreateGround = function (options) {
  27772. var indices = [];
  27773. var positions = [];
  27774. var normals = [];
  27775. var uvs = [];
  27776. var row, col;
  27777. var width = options.width || 1;
  27778. var height = options.height || 1;
  27779. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27780. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27781. for (row = 0; row <= subdivisionsY; row++) {
  27782. for (col = 0; col <= subdivisionsX; col++) {
  27783. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27784. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27785. positions.push(position.x, position.y, position.z);
  27786. normals.push(normal.x, normal.y, normal.z);
  27787. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27788. }
  27789. }
  27790. for (row = 0; row < subdivisionsY; row++) {
  27791. for (col = 0; col < subdivisionsX; col++) {
  27792. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27793. indices.push(col + 1 + row * (subdivisionsX + 1));
  27794. indices.push(col + row * (subdivisionsX + 1));
  27795. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27796. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27797. indices.push(col + row * (subdivisionsX + 1));
  27798. }
  27799. }
  27800. // Result
  27801. var vertexData = new VertexData();
  27802. vertexData.indices = indices;
  27803. vertexData.positions = positions;
  27804. vertexData.normals = normals;
  27805. vertexData.uvs = uvs;
  27806. return vertexData;
  27807. };
  27808. /**
  27809. * Creates the VertexData of the TiledGround.
  27810. */
  27811. VertexData.CreateTiledGround = function (options) {
  27812. var xmin = options.xmin || -1.0;
  27813. var zmin = options.zmin || -1.0;
  27814. var xmax = options.xmax || 1.0;
  27815. var zmax = options.zmax || 1.0;
  27816. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27817. var precision = options.precision || { w: 1, h: 1 };
  27818. var indices = [];
  27819. var positions = [];
  27820. var normals = [];
  27821. var uvs = [];
  27822. var row, col, tileRow, tileCol;
  27823. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27824. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27825. precision.w = (precision.w < 1) ? 1 : precision.w;
  27826. precision.h = (precision.h < 1) ? 1 : precision.h;
  27827. var tileSize = {
  27828. 'w': (xmax - xmin) / subdivisions.w,
  27829. 'h': (zmax - zmin) / subdivisions.h
  27830. };
  27831. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27832. // Indices
  27833. var base = positions.length / 3;
  27834. var rowLength = precision.w + 1;
  27835. for (row = 0; row < precision.h; row++) {
  27836. for (col = 0; col < precision.w; col++) {
  27837. var square = [
  27838. base + col + row * rowLength,
  27839. base + (col + 1) + row * rowLength,
  27840. base + (col + 1) + (row + 1) * rowLength,
  27841. base + col + (row + 1) * rowLength
  27842. ];
  27843. indices.push(square[1]);
  27844. indices.push(square[2]);
  27845. indices.push(square[3]);
  27846. indices.push(square[0]);
  27847. indices.push(square[1]);
  27848. indices.push(square[3]);
  27849. }
  27850. }
  27851. // Position, normals and uvs
  27852. var position = BABYLON.Vector3.Zero();
  27853. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27854. for (row = 0; row <= precision.h; row++) {
  27855. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27856. for (col = 0; col <= precision.w; col++) {
  27857. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27858. position.y = 0;
  27859. positions.push(position.x, position.y, position.z);
  27860. normals.push(normal.x, normal.y, normal.z);
  27861. uvs.push(col / precision.w, row / precision.h);
  27862. }
  27863. }
  27864. }
  27865. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27866. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27867. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27868. }
  27869. }
  27870. // Result
  27871. var vertexData = new VertexData();
  27872. vertexData.indices = indices;
  27873. vertexData.positions = positions;
  27874. vertexData.normals = normals;
  27875. vertexData.uvs = uvs;
  27876. return vertexData;
  27877. };
  27878. /**
  27879. * Creates the VertexData of the Ground designed from a heightmap.
  27880. */
  27881. VertexData.CreateGroundFromHeightMap = function (options) {
  27882. var indices = [];
  27883. var positions = [];
  27884. var normals = [];
  27885. var uvs = [];
  27886. var row, col;
  27887. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27888. // Vertices
  27889. for (row = 0; row <= options.subdivisions; row++) {
  27890. for (col = 0; col <= options.subdivisions; col++) {
  27891. 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));
  27892. // Compute height
  27893. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27894. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27895. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27896. var r = options.buffer[pos] / 255.0;
  27897. var g = options.buffer[pos + 1] / 255.0;
  27898. var b = options.buffer[pos + 2] / 255.0;
  27899. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27900. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27901. // Add vertex
  27902. positions.push(position.x, position.y, position.z);
  27903. normals.push(0, 0, 0);
  27904. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27905. }
  27906. }
  27907. // Indices
  27908. for (row = 0; row < options.subdivisions; row++) {
  27909. for (col = 0; col < options.subdivisions; col++) {
  27910. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27911. indices.push(col + 1 + row * (options.subdivisions + 1));
  27912. indices.push(col + row * (options.subdivisions + 1));
  27913. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27914. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27915. indices.push(col + row * (options.subdivisions + 1));
  27916. }
  27917. }
  27918. // Normals
  27919. VertexData.ComputeNormals(positions, indices, normals);
  27920. // Result
  27921. var vertexData = new VertexData();
  27922. vertexData.indices = indices;
  27923. vertexData.positions = positions;
  27924. vertexData.normals = normals;
  27925. vertexData.uvs = uvs;
  27926. return vertexData;
  27927. };
  27928. /**
  27929. * Creates the VertexData of the Plane.
  27930. */
  27931. VertexData.CreatePlane = function (options) {
  27932. var indices = [];
  27933. var positions = [];
  27934. var normals = [];
  27935. var uvs = [];
  27936. var width = options.width || options.size || 1;
  27937. var height = options.height || options.size || 1;
  27938. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27939. // Vertices
  27940. var halfWidth = width / 2.0;
  27941. var halfHeight = height / 2.0;
  27942. positions.push(-halfWidth, -halfHeight, 0);
  27943. normals.push(0, 0, -1.0);
  27944. uvs.push(0.0, 0.0);
  27945. positions.push(halfWidth, -halfHeight, 0);
  27946. normals.push(0, 0, -1.0);
  27947. uvs.push(1.0, 0.0);
  27948. positions.push(halfWidth, halfHeight, 0);
  27949. normals.push(0, 0, -1.0);
  27950. uvs.push(1.0, 1.0);
  27951. positions.push(-halfWidth, halfHeight, 0);
  27952. normals.push(0, 0, -1.0);
  27953. uvs.push(0.0, 1.0);
  27954. // Indices
  27955. indices.push(0);
  27956. indices.push(1);
  27957. indices.push(2);
  27958. indices.push(0);
  27959. indices.push(2);
  27960. indices.push(3);
  27961. // Sides
  27962. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27963. // Result
  27964. var vertexData = new VertexData();
  27965. vertexData.indices = indices;
  27966. vertexData.positions = positions;
  27967. vertexData.normals = normals;
  27968. vertexData.uvs = uvs;
  27969. return vertexData;
  27970. };
  27971. /**
  27972. * Creates the VertexData of the Disc or regular Polygon.
  27973. */
  27974. VertexData.CreateDisc = function (options) {
  27975. var positions = [];
  27976. var indices = [];
  27977. var normals = [];
  27978. var uvs = [];
  27979. var radius = options.radius || 0.5;
  27980. var tessellation = options.tessellation || 64;
  27981. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27983. // positions and uvs
  27984. positions.push(0, 0, 0); // disc center first
  27985. uvs.push(0.5, 0.5);
  27986. var theta = Math.PI * 2 * arc;
  27987. var step = theta / tessellation;
  27988. for (var a = 0; a < theta; a += step) {
  27989. var x = Math.cos(a);
  27990. var y = Math.sin(a);
  27991. var u = (x + 1) / 2;
  27992. var v = (1 - y) / 2;
  27993. positions.push(radius * x, radius * y, 0);
  27994. uvs.push(u, v);
  27995. }
  27996. if (arc === 1) {
  27997. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27998. uvs.push(uvs[2], uvs[3]);
  27999. }
  28000. //indices
  28001. var vertexNb = positions.length / 3;
  28002. for (var i = 1; i < vertexNb - 1; i++) {
  28003. indices.push(i + 1, 0, i);
  28004. }
  28005. // result
  28006. VertexData.ComputeNormals(positions, indices, normals);
  28007. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28008. var vertexData = new VertexData();
  28009. vertexData.indices = indices;
  28010. vertexData.positions = positions;
  28011. vertexData.normals = normals;
  28012. vertexData.uvs = uvs;
  28013. return vertexData;
  28014. };
  28015. /**
  28016. * Re-creates the VertexData of the Polygon for sideOrientation.
  28017. */
  28018. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28019. var faceUV = fUV || new Array(3);
  28020. var faceColors = fColors;
  28021. var colors = [];
  28022. // default face colors and UV if undefined
  28023. for (var f = 0; f < 3; f++) {
  28024. if (faceUV[f] === undefined) {
  28025. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28026. }
  28027. if (faceColors && faceColors[f] === undefined) {
  28028. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28029. }
  28030. }
  28031. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28032. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28033. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28034. var indices = polygon.getIndices();
  28035. // set face colours and textures
  28036. var idx = 0;
  28037. var face = 0;
  28038. for (var index = 0; index < normals.length; index += 3) {
  28039. //Edge Face no. 1
  28040. if (Math.abs(normals[index + 1]) < 0.001) {
  28041. face = 1;
  28042. }
  28043. //Top Face no. 0
  28044. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28045. face = 0;
  28046. }
  28047. //Bottom Face no. 2
  28048. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28049. face = 2;
  28050. }
  28051. idx = index / 3;
  28052. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28053. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28054. if (faceColors) {
  28055. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28056. }
  28057. }
  28058. // sides
  28059. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28060. // Result
  28061. var vertexData = new VertexData();
  28062. vertexData.indices = indices;
  28063. vertexData.positions = positions;
  28064. vertexData.normals = normals;
  28065. vertexData.uvs = uvs;
  28066. if (faceColors) {
  28067. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28068. vertexData.colors = totalColors;
  28069. }
  28070. return vertexData;
  28071. };
  28072. /**
  28073. * Creates the VertexData of the IcoSphere.
  28074. */
  28075. VertexData.CreateIcoSphere = function (options) {
  28076. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28077. var radius = options.radius || 1;
  28078. var flat = (options.flat === undefined) ? true : options.flat;
  28079. var subdivisions = options.subdivisions || 4;
  28080. var radiusX = options.radiusX || radius;
  28081. var radiusY = options.radiusY || radius;
  28082. var radiusZ = options.radiusZ || radius;
  28083. var t = (1 + Math.sqrt(5)) / 2;
  28084. // 12 vertex x,y,z
  28085. var ico_vertices = [
  28086. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28087. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28088. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28089. ];
  28090. // index of 3 vertex makes a face of icopshere
  28091. var ico_indices = [
  28092. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28093. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28094. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28095. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28096. ];
  28097. // vertex for uv have aliased position, not for UV
  28098. var vertices_unalias_id = [
  28099. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28100. // vertex alias
  28101. 0,
  28102. 2,
  28103. 3,
  28104. 3,
  28105. 3,
  28106. 4,
  28107. 7,
  28108. 8,
  28109. 9,
  28110. 9,
  28111. 10,
  28112. 11 // 23: B + 12
  28113. ];
  28114. // uv as integer step (not pixels !)
  28115. var ico_vertexuv = [
  28116. 5, 1, 3, 1, 6, 4, 0, 0,
  28117. 5, 3, 4, 2, 2, 2, 4, 0,
  28118. 2, 0, 1, 1, 6, 0, 6, 2,
  28119. // vertex alias (for same vertex on different faces)
  28120. 0, 4,
  28121. 3, 3,
  28122. 4, 4,
  28123. 3, 1,
  28124. 4, 2,
  28125. 4, 4,
  28126. 0, 2,
  28127. 1, 1,
  28128. 2, 2,
  28129. 3, 3,
  28130. 1, 3,
  28131. 2, 4 // 23: B + 12
  28132. ];
  28133. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28134. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28135. // First island of uv mapping
  28136. // v = 4h 3+ 2
  28137. // v = 3h 9+ 4
  28138. // v = 2h 9+ 5 B
  28139. // v = 1h 9 1 0
  28140. // v = 0h 3 8 7 A
  28141. // u = 0 1 2 3 4 5 6 *a
  28142. // Second island of uv mapping
  28143. // v = 4h 0+ B+ 4+
  28144. // v = 3h A+ 2+
  28145. // v = 2h 7+ 6 3+
  28146. // v = 1h 8+ 3+
  28147. // v = 0h
  28148. // u = 0 1 2 3 4 5 6 *a
  28149. // Face layout on texture UV mapping
  28150. // ============
  28151. // \ 4 /\ 16 / ======
  28152. // \ / \ / /\ 11 /
  28153. // \/ 7 \/ / \ /
  28154. // ======= / 10 \/
  28155. // /\ 17 /\ =======
  28156. // / \ / \ \ 15 /\
  28157. // / 8 \/ 12 \ \ / \
  28158. // ============ \/ 6 \
  28159. // \ 18 /\ ============
  28160. // \ / \ \ 5 /\ 0 /
  28161. // \/ 13 \ \ / \ /
  28162. // ======= \/ 1 \/
  28163. // =============
  28164. // /\ 19 /\ 2 /\
  28165. // / \ / \ / \
  28166. // / 14 \/ 9 \/ 3 \
  28167. // ===================
  28168. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28169. var ustep = 138 / 1024;
  28170. var vstep = 239 / 1024;
  28171. var uoffset = 60 / 1024;
  28172. var voffset = 26 / 1024;
  28173. // Second island should have margin, not to touch the first island
  28174. // avoid any borderline artefact in pixel rounding
  28175. var island_u_offset = -40 / 1024;
  28176. var island_v_offset = +20 / 1024;
  28177. // face is either island 0 or 1 :
  28178. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28179. var island = [
  28180. 0, 0, 0, 0, 1,
  28181. 0, 0, 1, 1, 0,
  28182. 0, 0, 1, 1, 0,
  28183. 0, 1, 1, 1, 0 // 15 - 19
  28184. ];
  28185. var indices = [];
  28186. var positions = [];
  28187. var normals = [];
  28188. var uvs = [];
  28189. var current_indice = 0;
  28190. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28191. var face_vertex_pos = new Array(3);
  28192. var face_vertex_uv = new Array(3);
  28193. var v012;
  28194. for (v012 = 0; v012 < 3; v012++) {
  28195. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28196. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28197. }
  28198. // create all with normals
  28199. for (var face = 0; face < 20; face++) {
  28200. // 3 vertex per face
  28201. for (v012 = 0; v012 < 3; v012++) {
  28202. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28203. var v_id = ico_indices[3 * face + v012];
  28204. // vertex have 3D position (x,y,z)
  28205. 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]);
  28206. // Normalize to get normal, then scale to radius
  28207. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28208. // uv Coordinates from vertex ID
  28209. 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);
  28210. }
  28211. // Subdivide the face (interpolate pos, norm, uv)
  28212. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28213. // - norm is linear interpolation of vertex corner normal
  28214. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28215. // - uv is linear interpolation
  28216. //
  28217. // Topology is as below for sub-divide by 2
  28218. // vertex shown as v0,v1,v2
  28219. // interp index is i1 to progress in range [v0,v1[
  28220. // interp index is i2 to progress in range [v0,v2[
  28221. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28222. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28223. //
  28224. //
  28225. // i2 v2
  28226. // ^ ^
  28227. // / / \
  28228. // / / \
  28229. // / / \
  28230. // / / (0,1) \
  28231. // / #---------\
  28232. // / / \ (0,0)'/ \
  28233. // / / \ / \
  28234. // / / \ / \
  28235. // / / (0,0) \ / (1,0) \
  28236. // / #---------#---------\
  28237. // v0 v1
  28238. //
  28239. // --------------------> i1
  28240. //
  28241. // interp of (i1,i2):
  28242. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28243. // along i1 : lerp(x0,x1, i1/(S-i2))
  28244. //
  28245. // centroid of triangle is needed to get help normal computation
  28246. // (c1,c2) are used for centroid location
  28247. var interp_vertex = function (i1, i2, c1, c2) {
  28248. // vertex is interpolated from
  28249. // - face_vertex_pos[0..2]
  28250. // - face_vertex_uv[0..2]
  28251. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28252. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28253. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28254. pos_interp.normalize();
  28255. var vertex_normal;
  28256. if (flat) {
  28257. // in flat mode, recalculate normal as face centroid normal
  28258. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28259. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28260. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28261. }
  28262. else {
  28263. // in smooth mode, recalculate normal from each single vertex position
  28264. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28265. }
  28266. // Vertex normal need correction due to X,Y,Z radius scaling
  28267. vertex_normal.x /= radiusX;
  28268. vertex_normal.y /= radiusY;
  28269. vertex_normal.z /= radiusZ;
  28270. vertex_normal.normalize();
  28271. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28272. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28273. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28274. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28275. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28276. uvs.push(uv_interp.x, uv_interp.y);
  28277. // push each vertex has member of a face
  28278. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28279. indices.push(current_indice);
  28280. current_indice++;
  28281. };
  28282. for (var i2 = 0; i2 < subdivisions; i2++) {
  28283. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28284. // face : (i1,i2) for /\ :
  28285. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28286. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28287. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28288. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28289. if (i1 + i2 + 1 < subdivisions) {
  28290. // face : (i1,i2)' for \/ :
  28291. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28292. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28293. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28294. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28295. }
  28296. }
  28297. }
  28298. }
  28299. // Sides
  28300. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28301. // Result
  28302. var vertexData = new VertexData();
  28303. vertexData.indices = indices;
  28304. vertexData.positions = positions;
  28305. vertexData.normals = normals;
  28306. vertexData.uvs = uvs;
  28307. return vertexData;
  28308. };
  28309. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28310. /**
  28311. * Creates the VertexData of the Polyhedron.
  28312. */
  28313. VertexData.CreatePolyhedron = function (options) {
  28314. // provided polyhedron types :
  28315. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28316. // 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)
  28317. var polyhedra = [];
  28318. 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]] };
  28319. 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]] };
  28320. polyhedra[2] = {
  28321. 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]],
  28322. 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]]
  28323. };
  28324. polyhedra[3] = {
  28325. 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]],
  28326. 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]]
  28327. };
  28328. polyhedra[4] = {
  28329. 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]],
  28330. 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]]
  28331. };
  28332. 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]] };
  28333. 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]] };
  28334. 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]] };
  28335. 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]] };
  28336. 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]] };
  28337. 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]] };
  28338. 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]] };
  28339. 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]] };
  28340. 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]] };
  28341. polyhedra[14] = {
  28342. 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]],
  28343. 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]]
  28344. };
  28345. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28346. var size = options.size;
  28347. var sizeX = options.sizeX || size || 1;
  28348. var sizeY = options.sizeY || size || 1;
  28349. var sizeZ = options.sizeZ || size || 1;
  28350. var data = options.custom || polyhedra[type];
  28351. var nbfaces = data.face.length;
  28352. var faceUV = options.faceUV || new Array(nbfaces);
  28353. var faceColors = options.faceColors;
  28354. var flat = (options.flat === undefined) ? true : options.flat;
  28355. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28356. var positions = [];
  28357. var indices = [];
  28358. var normals = [];
  28359. var uvs = [];
  28360. var colors = [];
  28361. var index = 0;
  28362. var faceIdx = 0; // face cursor in the array "indexes"
  28363. var indexes = [];
  28364. var i = 0;
  28365. var f = 0;
  28366. var u, v, ang, x, y, tmp;
  28367. // default face colors and UV if undefined
  28368. if (flat) {
  28369. for (f = 0; f < nbfaces; f++) {
  28370. if (faceColors && faceColors[f] === undefined) {
  28371. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28372. }
  28373. if (faceUV && faceUV[f] === undefined) {
  28374. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28375. }
  28376. }
  28377. }
  28378. if (!flat) {
  28379. for (i = 0; i < data.vertex.length; i++) {
  28380. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28381. uvs.push(0, 0);
  28382. }
  28383. for (f = 0; f < nbfaces; f++) {
  28384. for (i = 0; i < data.face[f].length - 2; i++) {
  28385. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28386. }
  28387. }
  28388. }
  28389. else {
  28390. for (f = 0; f < nbfaces; f++) {
  28391. var fl = data.face[f].length; // number of vertices of the current face
  28392. ang = 2 * Math.PI / fl;
  28393. x = 0.5 * Math.tan(ang / 2);
  28394. y = 0.5;
  28395. // positions, uvs, colors
  28396. for (i = 0; i < fl; i++) {
  28397. // positions
  28398. 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);
  28399. indexes.push(index);
  28400. index++;
  28401. // uvs
  28402. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28403. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28404. uvs.push(u, v);
  28405. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28406. y = x * Math.sin(ang) + y * Math.cos(ang);
  28407. x = tmp;
  28408. // colors
  28409. if (faceColors) {
  28410. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28411. }
  28412. }
  28413. // indices from indexes
  28414. for (i = 0; i < fl - 2; i++) {
  28415. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28416. }
  28417. faceIdx += fl;
  28418. }
  28419. }
  28420. VertexData.ComputeNormals(positions, indices, normals);
  28421. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28422. var vertexData = new VertexData();
  28423. vertexData.positions = positions;
  28424. vertexData.indices = indices;
  28425. vertexData.normals = normals;
  28426. vertexData.uvs = uvs;
  28427. if (faceColors && flat) {
  28428. vertexData.colors = colors;
  28429. }
  28430. return vertexData;
  28431. };
  28432. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28433. /**
  28434. * Creates the VertexData of the Torus Knot.
  28435. */
  28436. VertexData.CreateTorusKnot = function (options) {
  28437. var indices = [];
  28438. var positions = [];
  28439. var normals = [];
  28440. var uvs = [];
  28441. var radius = options.radius || 2;
  28442. var tube = options.tube || 0.5;
  28443. var radialSegments = options.radialSegments || 32;
  28444. var tubularSegments = options.tubularSegments || 32;
  28445. var p = options.p || 2;
  28446. var q = options.q || 3;
  28447. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28448. // Helper
  28449. var getPos = function (angle) {
  28450. var cu = Math.cos(angle);
  28451. var su = Math.sin(angle);
  28452. var quOverP = q / p * angle;
  28453. var cs = Math.cos(quOverP);
  28454. var tx = radius * (2 + cs) * 0.5 * cu;
  28455. var ty = radius * (2 + cs) * su * 0.5;
  28456. var tz = radius * Math.sin(quOverP) * 0.5;
  28457. return new BABYLON.Vector3(tx, ty, tz);
  28458. };
  28459. // Vertices
  28460. var i;
  28461. var j;
  28462. for (i = 0; i <= radialSegments; i++) {
  28463. var modI = i % radialSegments;
  28464. var u = modI / radialSegments * 2 * p * Math.PI;
  28465. var p1 = getPos(u);
  28466. var p2 = getPos(u + 0.01);
  28467. var tang = p2.subtract(p1);
  28468. var n = p2.add(p1);
  28469. var bitan = BABYLON.Vector3.Cross(tang, n);
  28470. n = BABYLON.Vector3.Cross(bitan, tang);
  28471. bitan.normalize();
  28472. n.normalize();
  28473. for (j = 0; j < tubularSegments; j++) {
  28474. var modJ = j % tubularSegments;
  28475. var v = modJ / tubularSegments * 2 * Math.PI;
  28476. var cx = -tube * Math.cos(v);
  28477. var cy = tube * Math.sin(v);
  28478. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28479. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28480. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28481. uvs.push(i / radialSegments);
  28482. uvs.push(j / tubularSegments);
  28483. }
  28484. }
  28485. for (i = 0; i < radialSegments; i++) {
  28486. for (j = 0; j < tubularSegments; j++) {
  28487. var jNext = (j + 1) % tubularSegments;
  28488. var a = i * tubularSegments + j;
  28489. var b = (i + 1) * tubularSegments + j;
  28490. var c = (i + 1) * tubularSegments + jNext;
  28491. var d = i * tubularSegments + jNext;
  28492. indices.push(d);
  28493. indices.push(b);
  28494. indices.push(a);
  28495. indices.push(d);
  28496. indices.push(c);
  28497. indices.push(b);
  28498. }
  28499. }
  28500. // Normals
  28501. VertexData.ComputeNormals(positions, indices, normals);
  28502. // Sides
  28503. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28504. // Result
  28505. var vertexData = new VertexData();
  28506. vertexData.indices = indices;
  28507. vertexData.positions = positions;
  28508. vertexData.normals = normals;
  28509. vertexData.uvs = uvs;
  28510. return vertexData;
  28511. };
  28512. // Tools
  28513. /**
  28514. * @param {any} - positions (number[] or Float32Array)
  28515. * @param {any} - indices (number[] or Uint16Array)
  28516. * @param {any} - normals (number[] or Float32Array)
  28517. * options (optional) :
  28518. * facetPositions : optional array of facet positions (vector3)
  28519. * facetNormals : optional array of facet normals (vector3)
  28520. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28521. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28522. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28523. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28524. * bInfo : optional bounding info, required for facetPartitioning computation
  28525. */
  28526. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28527. // temporary scalar variables
  28528. var index = 0; // facet index
  28529. var p1p2x = 0.0; // p1p2 vector x coordinate
  28530. var p1p2y = 0.0; // p1p2 vector y coordinate
  28531. var p1p2z = 0.0; // p1p2 vector z coordinate
  28532. var p3p2x = 0.0; // p3p2 vector x coordinate
  28533. var p3p2y = 0.0; // p3p2 vector y coordinate
  28534. var p3p2z = 0.0; // p3p2 vector z coordinate
  28535. var faceNormalx = 0.0; // facet normal x coordinate
  28536. var faceNormaly = 0.0; // facet normal y coordinate
  28537. var faceNormalz = 0.0; // facet normal z coordinate
  28538. var length = 0.0; // facet normal length before normalization
  28539. var v1x = 0; // vector1 x index in the positions array
  28540. var v1y = 0; // vector1 y index in the positions array
  28541. var v1z = 0; // vector1 z index in the positions array
  28542. var v2x = 0; // vector2 x index in the positions array
  28543. var v2y = 0; // vector2 y index in the positions array
  28544. var v2z = 0; // vector2 z index in the positions array
  28545. var v3x = 0; // vector3 x index in the positions array
  28546. var v3y = 0; // vector3 y index in the positions array
  28547. var v3z = 0; // vector3 z index in the positions array
  28548. var computeFacetNormals = false;
  28549. var computeFacetPositions = false;
  28550. var computeFacetPartitioning = false;
  28551. var faceNormalSign = 1;
  28552. if (options) {
  28553. computeFacetNormals = (options.facetNormals) ? true : false;
  28554. computeFacetPositions = (options.facetPositions) ? true : false;
  28555. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28556. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28557. }
  28558. // facetPartitioning reinit if needed
  28559. if (computeFacetPartitioning) {
  28560. var ox = 0; // X partitioning index for facet position
  28561. var oy = 0; // Y partinioning index for facet position
  28562. var oz = 0; // Z partinioning index for facet position
  28563. var b1x = 0; // X partitioning index for facet v1 vertex
  28564. var b1y = 0; // Y partitioning index for facet v1 vertex
  28565. var b1z = 0; // z partitioning index for facet v1 vertex
  28566. var b2x = 0; // X partitioning index for facet v2 vertex
  28567. var b2y = 0; // Y partitioning index for facet v2 vertex
  28568. var b2z = 0; // Z partitioning index for facet v2 vertex
  28569. var b3x = 0; // X partitioning index for facet v3 vertex
  28570. var b3y = 0; // Y partitioning index for facet v3 vertex
  28571. var b3z = 0; // Z partitioning index for facet v3 vertex
  28572. var block_idx_o = 0; // facet barycenter block index
  28573. var block_idx_v1 = 0; // v1 vertex block index
  28574. var block_idx_v2 = 0; // v2 vertex block index
  28575. var block_idx_v3 = 0; // v3 vertex block index
  28576. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28577. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28578. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28579. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28580. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28581. var subSq = options.subDiv.max * options.subDiv.max;
  28582. options.facetPartitioning.length = 0;
  28583. }
  28584. // reset the normals
  28585. for (index = 0; index < positions.length; index++) {
  28586. normals[index] = 0.0;
  28587. }
  28588. // Loop : 1 indice triplet = 1 facet
  28589. var nbFaces = indices.length / 3;
  28590. for (index = 0; index < nbFaces; index++) {
  28591. // get the indexes of the coordinates of each vertex of the facet
  28592. v1x = indices[index * 3] * 3;
  28593. v1y = v1x + 1;
  28594. v1z = v1x + 2;
  28595. v2x = indices[index * 3 + 1] * 3;
  28596. v2y = v2x + 1;
  28597. v2z = v2x + 2;
  28598. v3x = indices[index * 3 + 2] * 3;
  28599. v3y = v3x + 1;
  28600. v3z = v3x + 2;
  28601. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28602. p1p2y = positions[v1y] - positions[v2y];
  28603. p1p2z = positions[v1z] - positions[v2z];
  28604. p3p2x = positions[v3x] - positions[v2x];
  28605. p3p2y = positions[v3y] - positions[v2y];
  28606. p3p2z = positions[v3z] - positions[v2z];
  28607. // compute the face normal with the cross product
  28608. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28609. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28610. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28611. // normalize this normal and store it in the array facetData
  28612. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28613. length = (length === 0) ? 1.0 : length;
  28614. faceNormalx /= length;
  28615. faceNormaly /= length;
  28616. faceNormalz /= length;
  28617. if (computeFacetNormals) {
  28618. options.facetNormals[index].x = faceNormalx;
  28619. options.facetNormals[index].y = faceNormaly;
  28620. options.facetNormals[index].z = faceNormalz;
  28621. }
  28622. if (computeFacetPositions) {
  28623. // compute and the facet barycenter coordinates in the array facetPositions
  28624. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28625. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28626. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28627. }
  28628. if (computeFacetPartitioning) {
  28629. // store the facet indexes in arrays in the main facetPartitioning array :
  28630. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28631. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28632. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28633. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28634. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28635. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28636. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28637. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28638. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28639. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28640. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28641. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28642. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28643. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28644. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28645. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28646. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28647. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28648. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28649. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28650. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28651. // push each facet index in each block containing the vertex
  28652. options.facetPartitioning[block_idx_v1].push(index);
  28653. if (block_idx_v2 != block_idx_v1) {
  28654. options.facetPartitioning[block_idx_v2].push(index);
  28655. }
  28656. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28657. options.facetPartitioning[block_idx_v3].push(index);
  28658. }
  28659. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28660. options.facetPartitioning[block_idx_o].push(index);
  28661. }
  28662. }
  28663. // compute the normals anyway
  28664. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28665. normals[v1y] += faceNormaly;
  28666. normals[v1z] += faceNormalz;
  28667. normals[v2x] += faceNormalx;
  28668. normals[v2y] += faceNormaly;
  28669. normals[v2z] += faceNormalz;
  28670. normals[v3x] += faceNormalx;
  28671. normals[v3y] += faceNormaly;
  28672. normals[v3z] += faceNormalz;
  28673. }
  28674. // last normalization of each normal
  28675. for (index = 0; index < normals.length / 3; index++) {
  28676. faceNormalx = normals[index * 3];
  28677. faceNormaly = normals[index * 3 + 1];
  28678. faceNormalz = normals[index * 3 + 2];
  28679. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28680. length = (length === 0) ? 1.0 : length;
  28681. faceNormalx /= length;
  28682. faceNormaly /= length;
  28683. faceNormalz /= length;
  28684. normals[index * 3] = faceNormalx;
  28685. normals[index * 3 + 1] = faceNormaly;
  28686. normals[index * 3 + 2] = faceNormalz;
  28687. }
  28688. };
  28689. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28690. var li = indices.length;
  28691. var ln = normals.length;
  28692. var i;
  28693. var n;
  28694. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28695. switch (sideOrientation) {
  28696. case BABYLON.Mesh.FRONTSIDE:
  28697. // nothing changed
  28698. break;
  28699. case BABYLON.Mesh.BACKSIDE:
  28700. var tmp;
  28701. // indices
  28702. for (i = 0; i < li; i += 3) {
  28703. tmp = indices[i];
  28704. indices[i] = indices[i + 2];
  28705. indices[i + 2] = tmp;
  28706. }
  28707. // normals
  28708. for (n = 0; n < ln; n++) {
  28709. normals[n] = -normals[n];
  28710. }
  28711. break;
  28712. case BABYLON.Mesh.DOUBLESIDE:
  28713. // positions
  28714. var lp = positions.length;
  28715. var l = lp / 3;
  28716. for (var p = 0; p < lp; p++) {
  28717. positions[lp + p] = positions[p];
  28718. }
  28719. // indices
  28720. for (i = 0; i < li; i += 3) {
  28721. indices[i + li] = indices[i + 2] + l;
  28722. indices[i + 1 + li] = indices[i + 1] + l;
  28723. indices[i + 2 + li] = indices[i] + l;
  28724. }
  28725. // normals
  28726. for (n = 0; n < ln; n++) {
  28727. normals[ln + n] = -normals[n];
  28728. }
  28729. // uvs
  28730. var lu = uvs.length;
  28731. var u = 0;
  28732. for (u = 0; u < lu; u++) {
  28733. uvs[u + lu] = uvs[u];
  28734. }
  28735. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28736. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28737. u = 0;
  28738. for (i = 0; i < lu / 2; i++) {
  28739. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28740. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28741. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28742. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28743. u += 2;
  28744. }
  28745. break;
  28746. }
  28747. };
  28748. /**
  28749. * Creates a new VertexData from the imported parameters.
  28750. */
  28751. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28752. var vertexData = new VertexData();
  28753. // positions
  28754. var positions = parsedVertexData.positions;
  28755. if (positions) {
  28756. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28757. }
  28758. // normals
  28759. var normals = parsedVertexData.normals;
  28760. if (normals) {
  28761. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28762. }
  28763. // tangents
  28764. var tangents = parsedVertexData.tangents;
  28765. if (tangents) {
  28766. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28767. }
  28768. // uvs
  28769. var uvs = parsedVertexData.uvs;
  28770. if (uvs) {
  28771. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28772. }
  28773. // uv2s
  28774. var uv2s = parsedVertexData.uv2s;
  28775. if (uv2s) {
  28776. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28777. }
  28778. // uv3s
  28779. var uv3s = parsedVertexData.uv3s;
  28780. if (uv3s) {
  28781. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28782. }
  28783. // uv4s
  28784. var uv4s = parsedVertexData.uv4s;
  28785. if (uv4s) {
  28786. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28787. }
  28788. // uv5s
  28789. var uv5s = parsedVertexData.uv5s;
  28790. if (uv5s) {
  28791. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28792. }
  28793. // uv6s
  28794. var uv6s = parsedVertexData.uv6s;
  28795. if (uv6s) {
  28796. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28797. }
  28798. // colors
  28799. var colors = parsedVertexData.colors;
  28800. if (colors) {
  28801. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28802. }
  28803. // matricesIndices
  28804. var matricesIndices = parsedVertexData.matricesIndices;
  28805. if (matricesIndices) {
  28806. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28807. }
  28808. // matricesWeights
  28809. var matricesWeights = parsedVertexData.matricesWeights;
  28810. if (matricesWeights) {
  28811. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28812. }
  28813. // indices
  28814. var indices = parsedVertexData.indices;
  28815. if (indices) {
  28816. vertexData.indices = indices;
  28817. }
  28818. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28819. };
  28820. return VertexData;
  28821. }());
  28822. BABYLON.VertexData = VertexData;
  28823. })(BABYLON || (BABYLON = {}));
  28824. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28825. var BABYLON;
  28826. (function (BABYLON) {
  28827. var Geometry = (function () {
  28828. function Geometry(id, scene, vertexData, updatable, mesh) {
  28829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28830. this._totalVertices = 0;
  28831. this._isDisposed = false;
  28832. this.id = id;
  28833. this._engine = scene.getEngine();
  28834. this._meshes = [];
  28835. this._scene = scene;
  28836. //Init vertex buffer cache
  28837. this._vertexBuffers = {};
  28838. this._indices = [];
  28839. this._updatable = updatable;
  28840. // vertexData
  28841. if (vertexData) {
  28842. this.setAllVerticesData(vertexData, updatable);
  28843. }
  28844. else {
  28845. this._totalVertices = 0;
  28846. this._indices = [];
  28847. }
  28848. if (this._engine.getCaps().vertexArrayObject) {
  28849. this._vertexArrayObjects = {};
  28850. }
  28851. // applyToMesh
  28852. if (mesh) {
  28853. if (mesh.getClassName() === "LinesMesh") {
  28854. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28855. this.updateExtend();
  28856. }
  28857. this.applyToMesh(mesh);
  28858. mesh.computeWorldMatrix(true);
  28859. }
  28860. }
  28861. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28862. /**
  28863. * 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
  28864. * @returns The Bias Vector
  28865. */
  28866. get: function () {
  28867. return this._boundingBias;
  28868. },
  28869. set: function (value) {
  28870. if (this._boundingBias && this._boundingBias.equals(value)) {
  28871. return;
  28872. }
  28873. this._boundingBias = value.clone();
  28874. this.updateBoundingInfo(true, null);
  28875. },
  28876. enumerable: true,
  28877. configurable: true
  28878. });
  28879. Object.defineProperty(Geometry.prototype, "extend", {
  28880. get: function () {
  28881. return this._extend;
  28882. },
  28883. enumerable: true,
  28884. configurable: true
  28885. });
  28886. Geometry.prototype.getScene = function () {
  28887. return this._scene;
  28888. };
  28889. Geometry.prototype.getEngine = function () {
  28890. return this._engine;
  28891. };
  28892. Geometry.prototype.isReady = function () {
  28893. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28894. };
  28895. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28896. get: function () {
  28897. for (var index = 0; index < this._meshes.length; index++) {
  28898. if (!this._meshes[index].doNotSerialize) {
  28899. return false;
  28900. }
  28901. }
  28902. return true;
  28903. },
  28904. enumerable: true,
  28905. configurable: true
  28906. });
  28907. Geometry.prototype._rebuild = function () {
  28908. if (this._vertexArrayObjects) {
  28909. this._vertexArrayObjects = {};
  28910. }
  28911. // Index buffer
  28912. if (this._meshes.length !== 0 && this._indices) {
  28913. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28914. }
  28915. // Vertex buffers
  28916. for (var key in this._vertexBuffers) {
  28917. var vertexBuffer = this._vertexBuffers[key];
  28918. vertexBuffer._rebuild();
  28919. }
  28920. };
  28921. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28922. vertexData.applyToGeometry(this, updatable);
  28923. this.notifyUpdate();
  28924. };
  28925. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28926. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28927. this.setVerticesBuffer(buffer);
  28928. };
  28929. Geometry.prototype.removeVerticesData = function (kind) {
  28930. if (this._vertexBuffers[kind]) {
  28931. this._vertexBuffers[kind].dispose();
  28932. delete this._vertexBuffers[kind];
  28933. }
  28934. };
  28935. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28936. var kind = buffer.getKind();
  28937. if (this._vertexBuffers[kind]) {
  28938. this._vertexBuffers[kind].dispose();
  28939. }
  28940. this._vertexBuffers[kind] = buffer;
  28941. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28942. var data = buffer.getData();
  28943. var stride = buffer.getStrideSize();
  28944. this._totalVertices = data.length / stride;
  28945. this.updateExtend(data, stride);
  28946. this._resetPointsArrayCache();
  28947. var meshes = this._meshes;
  28948. var numOfMeshes = meshes.length;
  28949. for (var index = 0; index < numOfMeshes; index++) {
  28950. var mesh = meshes[index];
  28951. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28952. mesh._createGlobalSubMesh(false);
  28953. mesh.computeWorldMatrix(true);
  28954. }
  28955. }
  28956. this.notifyUpdate(kind);
  28957. if (this._vertexArrayObjects) {
  28958. this._disposeVertexArrayObjects();
  28959. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28960. }
  28961. };
  28962. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28963. var vertexBuffer = this.getVertexBuffer(kind);
  28964. if (!vertexBuffer) {
  28965. return;
  28966. }
  28967. vertexBuffer.updateDirectly(data, offset);
  28968. this.notifyUpdate(kind);
  28969. };
  28970. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28971. var vertexBuffer = this.getVertexBuffer(kind);
  28972. if (!vertexBuffer) {
  28973. return;
  28974. }
  28975. vertexBuffer.update(data);
  28976. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28977. var stride = vertexBuffer.getStrideSize();
  28978. this._totalVertices = data.length / stride;
  28979. this.updateBoundingInfo(updateExtends, data);
  28980. }
  28981. this.notifyUpdate(kind);
  28982. };
  28983. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28984. if (updateExtends) {
  28985. this.updateExtend(data);
  28986. }
  28987. var meshes = this._meshes;
  28988. var numOfMeshes = meshes.length;
  28989. this._resetPointsArrayCache();
  28990. for (var index = 0; index < numOfMeshes; index++) {
  28991. var mesh = meshes[index];
  28992. if (updateExtends) {
  28993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28994. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28995. var subMesh = mesh.subMeshes[subIndex];
  28996. subMesh.refreshBoundingInfo();
  28997. }
  28998. }
  28999. }
  29000. };
  29001. Geometry.prototype._bind = function (effect, indexToBind) {
  29002. if (indexToBind === void 0) { indexToBind = undefined; }
  29003. if (indexToBind === undefined) {
  29004. indexToBind = this._indexBuffer;
  29005. }
  29006. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29007. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29008. return;
  29009. }
  29010. // Using VAO
  29011. if (!this._vertexArrayObjects[effect.key]) {
  29012. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29013. }
  29014. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29015. };
  29016. Geometry.prototype.getTotalVertices = function () {
  29017. if (!this.isReady()) {
  29018. return 0;
  29019. }
  29020. return this._totalVertices;
  29021. };
  29022. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29023. var vertexBuffer = this.getVertexBuffer(kind);
  29024. if (!vertexBuffer) {
  29025. return null;
  29026. }
  29027. var orig = vertexBuffer.getData();
  29028. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29029. return orig;
  29030. }
  29031. else {
  29032. var len = orig.length;
  29033. var copy = [];
  29034. for (var i = 0; i < len; i++) {
  29035. copy.push(orig[i]);
  29036. }
  29037. return copy;
  29038. }
  29039. };
  29040. Geometry.prototype.getVertexBuffer = function (kind) {
  29041. if (!this.isReady()) {
  29042. return null;
  29043. }
  29044. return this._vertexBuffers[kind];
  29045. };
  29046. Geometry.prototype.getVertexBuffers = function () {
  29047. if (!this.isReady()) {
  29048. return null;
  29049. }
  29050. return this._vertexBuffers;
  29051. };
  29052. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29053. if (!this._vertexBuffers) {
  29054. if (this._delayInfo) {
  29055. return this._delayInfo.indexOf(kind) !== -1;
  29056. }
  29057. return false;
  29058. }
  29059. return this._vertexBuffers[kind] !== undefined;
  29060. };
  29061. Geometry.prototype.getVerticesDataKinds = function () {
  29062. var result = [];
  29063. var kind;
  29064. if (!this._vertexBuffers && this._delayInfo) {
  29065. for (kind in this._delayInfo) {
  29066. result.push(kind);
  29067. }
  29068. }
  29069. else {
  29070. for (kind in this._vertexBuffers) {
  29071. result.push(kind);
  29072. }
  29073. }
  29074. return result;
  29075. };
  29076. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29077. if (this._indexBuffer) {
  29078. this._engine._releaseBuffer(this._indexBuffer);
  29079. }
  29080. this._disposeVertexArrayObjects();
  29081. this._indices = indices;
  29082. if (this._meshes.length !== 0 && this._indices) {
  29083. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29084. }
  29085. if (totalVertices !== undefined) {
  29086. this._totalVertices = totalVertices;
  29087. }
  29088. var meshes = this._meshes;
  29089. var numOfMeshes = meshes.length;
  29090. for (var index = 0; index < numOfMeshes; index++) {
  29091. meshes[index]._createGlobalSubMesh(true);
  29092. }
  29093. this.notifyUpdate();
  29094. };
  29095. Geometry.prototype.getTotalIndices = function () {
  29096. if (!this.isReady()) {
  29097. return 0;
  29098. }
  29099. return this._indices.length;
  29100. };
  29101. Geometry.prototype.getIndices = function (copyWhenShared) {
  29102. if (!this.isReady()) {
  29103. return null;
  29104. }
  29105. var orig = this._indices;
  29106. if (!copyWhenShared || this._meshes.length === 1) {
  29107. return orig;
  29108. }
  29109. else {
  29110. var len = orig.length;
  29111. var copy = [];
  29112. for (var i = 0; i < len; i++) {
  29113. copy.push(orig[i]);
  29114. }
  29115. return copy;
  29116. }
  29117. };
  29118. Geometry.prototype.getIndexBuffer = function () {
  29119. if (!this.isReady()) {
  29120. return null;
  29121. }
  29122. return this._indexBuffer;
  29123. };
  29124. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29125. if (!effect || !this._vertexArrayObjects) {
  29126. return;
  29127. }
  29128. if (this._vertexArrayObjects[effect.key]) {
  29129. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29130. delete this._vertexArrayObjects[effect.key];
  29131. }
  29132. };
  29133. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29134. var meshes = this._meshes;
  29135. var index = meshes.indexOf(mesh);
  29136. if (index === -1) {
  29137. return;
  29138. }
  29139. meshes.splice(index, 1);
  29140. mesh._geometry = null;
  29141. if (meshes.length === 0 && shouldDispose) {
  29142. this.dispose();
  29143. }
  29144. };
  29145. Geometry.prototype.applyToMesh = function (mesh) {
  29146. if (mesh._geometry === this) {
  29147. return;
  29148. }
  29149. var previousGeometry = mesh._geometry;
  29150. if (previousGeometry) {
  29151. previousGeometry.releaseForMesh(mesh);
  29152. }
  29153. var meshes = this._meshes;
  29154. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29155. mesh._geometry = this;
  29156. this._scene.pushGeometry(this);
  29157. meshes.push(mesh);
  29158. if (this.isReady()) {
  29159. this._applyToMesh(mesh);
  29160. }
  29161. else {
  29162. mesh._boundingInfo = this._boundingInfo;
  29163. }
  29164. };
  29165. Geometry.prototype.updateExtend = function (data, stride) {
  29166. if (data === void 0) { data = null; }
  29167. if (!data) {
  29168. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29169. }
  29170. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29171. };
  29172. Geometry.prototype._applyToMesh = function (mesh) {
  29173. var numOfMeshes = this._meshes.length;
  29174. // vertexBuffers
  29175. for (var kind in this._vertexBuffers) {
  29176. if (numOfMeshes === 1) {
  29177. this._vertexBuffers[kind].create();
  29178. }
  29179. var buffer = this._vertexBuffers[kind].getBuffer();
  29180. if (buffer)
  29181. buffer.references = numOfMeshes;
  29182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29183. if (!this._extend) {
  29184. this.updateExtend(this._vertexBuffers[kind].getData());
  29185. }
  29186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29187. mesh._createGlobalSubMesh(false);
  29188. //bounding info was just created again, world matrix should be applied again.
  29189. mesh._updateBoundingInfo();
  29190. }
  29191. }
  29192. // indexBuffer
  29193. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29194. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29195. }
  29196. if (this._indexBuffer) {
  29197. this._indexBuffer.references = numOfMeshes;
  29198. }
  29199. };
  29200. Geometry.prototype.notifyUpdate = function (kind) {
  29201. if (this.onGeometryUpdated) {
  29202. this.onGeometryUpdated(this, kind);
  29203. }
  29204. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29205. var mesh = _a[_i];
  29206. mesh._markSubMeshesAsAttributesDirty();
  29207. }
  29208. };
  29209. Geometry.prototype.load = function (scene, onLoaded) {
  29210. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29211. return;
  29212. }
  29213. if (this.isReady()) {
  29214. if (onLoaded) {
  29215. onLoaded();
  29216. }
  29217. return;
  29218. }
  29219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29220. this._queueLoad(scene, onLoaded);
  29221. };
  29222. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29223. var _this = this;
  29224. scene._addPendingData(this);
  29225. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29226. _this._delayLoadingFunction(JSON.parse(data), _this);
  29227. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29228. _this._delayInfo = [];
  29229. scene._removePendingData(_this);
  29230. var meshes = _this._meshes;
  29231. var numOfMeshes = meshes.length;
  29232. for (var index = 0; index < numOfMeshes; index++) {
  29233. _this._applyToMesh(meshes[index]);
  29234. }
  29235. if (onLoaded) {
  29236. onLoaded();
  29237. }
  29238. }, function () { }, scene.database);
  29239. };
  29240. /**
  29241. * Invert the geometry to move from a right handed system to a left handed one.
  29242. */
  29243. Geometry.prototype.toLeftHanded = function () {
  29244. // Flip faces
  29245. var tIndices = this.getIndices(false);
  29246. if (tIndices != null && tIndices.length > 0) {
  29247. for (var i = 0; i < tIndices.length; i += 3) {
  29248. var tTemp = tIndices[i + 0];
  29249. tIndices[i + 0] = tIndices[i + 2];
  29250. tIndices[i + 2] = tTemp;
  29251. }
  29252. this.setIndices(tIndices);
  29253. }
  29254. // Negate position.z
  29255. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29256. if (tPositions != null && tPositions.length > 0) {
  29257. for (var i = 0; i < tPositions.length; i += 3) {
  29258. tPositions[i + 2] = -tPositions[i + 2];
  29259. }
  29260. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29261. }
  29262. // Negate normal.z
  29263. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29264. if (tNormals != null && tNormals.length > 0) {
  29265. for (var i = 0; i < tNormals.length; i += 3) {
  29266. tNormals[i + 2] = -tNormals[i + 2];
  29267. }
  29268. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29269. }
  29270. };
  29271. // Cache
  29272. Geometry.prototype._resetPointsArrayCache = function () {
  29273. this._positions = null;
  29274. };
  29275. Geometry.prototype._generatePointsArray = function () {
  29276. if (this._positions)
  29277. return true;
  29278. this._positions = [];
  29279. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29280. if (!data) {
  29281. return false;
  29282. }
  29283. for (var index = 0; index < data.length; index += 3) {
  29284. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29285. }
  29286. return true;
  29287. };
  29288. Geometry.prototype.isDisposed = function () {
  29289. return this._isDisposed;
  29290. };
  29291. Geometry.prototype._disposeVertexArrayObjects = function () {
  29292. if (this._vertexArrayObjects) {
  29293. for (var kind in this._vertexArrayObjects) {
  29294. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29295. }
  29296. this._vertexArrayObjects = {};
  29297. }
  29298. };
  29299. Geometry.prototype.dispose = function () {
  29300. var meshes = this._meshes;
  29301. var numOfMeshes = meshes.length;
  29302. var index;
  29303. for (index = 0; index < numOfMeshes; index++) {
  29304. this.releaseForMesh(meshes[index]);
  29305. }
  29306. this._meshes = [];
  29307. this._disposeVertexArrayObjects();
  29308. for (var kind in this._vertexBuffers) {
  29309. this._vertexBuffers[kind].dispose();
  29310. }
  29311. this._vertexBuffers = {};
  29312. this._totalVertices = 0;
  29313. if (this._indexBuffer) {
  29314. this._engine._releaseBuffer(this._indexBuffer);
  29315. }
  29316. this._indexBuffer = null;
  29317. this._indices = [];
  29318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29319. this.delayLoadingFile = null;
  29320. this._delayLoadingFunction = null;
  29321. this._delayInfo = [];
  29322. this._boundingInfo = null;
  29323. this._scene.removeGeometry(this);
  29324. this._isDisposed = true;
  29325. };
  29326. Geometry.prototype.copy = function (id) {
  29327. var vertexData = new BABYLON.VertexData();
  29328. vertexData.indices = [];
  29329. var indices = this.getIndices();
  29330. for (var index = 0; index < indices.length; index++) {
  29331. vertexData.indices.push(indices[index]);
  29332. }
  29333. var updatable = false;
  29334. var stopChecking = false;
  29335. var kind;
  29336. for (kind in this._vertexBuffers) {
  29337. // using slice() to make a copy of the array and not just reference it
  29338. var data = this.getVerticesData(kind);
  29339. if (data instanceof Float32Array) {
  29340. vertexData.set(new Float32Array(data), kind);
  29341. }
  29342. else {
  29343. vertexData.set(data.slice(0), kind);
  29344. }
  29345. if (!stopChecking) {
  29346. updatable = this.getVertexBuffer(kind).isUpdatable();
  29347. stopChecking = !updatable;
  29348. }
  29349. }
  29350. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29351. geometry.delayLoadState = this.delayLoadState;
  29352. geometry.delayLoadingFile = this.delayLoadingFile;
  29353. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29354. for (kind in this._delayInfo) {
  29355. geometry._delayInfo = geometry._delayInfo || [];
  29356. geometry._delayInfo.push(kind);
  29357. }
  29358. // Bounding info
  29359. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29360. return geometry;
  29361. };
  29362. Geometry.prototype.serialize = function () {
  29363. var serializationObject = {};
  29364. serializationObject.id = this.id;
  29365. serializationObject.updatable = this._updatable;
  29366. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29367. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29368. }
  29369. return serializationObject;
  29370. };
  29371. Geometry.prototype.toNumberArray = function (origin) {
  29372. if (Array.isArray(origin)) {
  29373. return origin;
  29374. }
  29375. else {
  29376. return Array.prototype.slice.call(origin);
  29377. }
  29378. };
  29379. Geometry.prototype.serializeVerticeData = function () {
  29380. var serializationObject = this.serialize();
  29381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29382. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29383. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29384. serializationObject.positions._updatable = true;
  29385. }
  29386. }
  29387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29388. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29389. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29390. serializationObject.normals._updatable = true;
  29391. }
  29392. }
  29393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29394. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29395. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29396. serializationObject.uvs._updatable = true;
  29397. }
  29398. }
  29399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29400. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29401. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29402. serializationObject.uv2s._updatable = true;
  29403. }
  29404. }
  29405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29406. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29407. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29408. serializationObject.uv3s._updatable = true;
  29409. }
  29410. }
  29411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29412. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29413. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29414. serializationObject.uv4s._updatable = true;
  29415. }
  29416. }
  29417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29418. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29419. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29420. serializationObject.uv5s._updatable = true;
  29421. }
  29422. }
  29423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29424. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29425. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29426. serializationObject.uv6s._updatable = true;
  29427. }
  29428. }
  29429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29430. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29431. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29432. serializationObject.colors._updatable = true;
  29433. }
  29434. }
  29435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29436. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29437. serializationObject.matricesIndices._isExpanded = true;
  29438. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29439. serializationObject.matricesIndices._updatable = true;
  29440. }
  29441. }
  29442. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29443. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29444. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29445. serializationObject.matricesWeights._updatable = true;
  29446. }
  29447. }
  29448. serializationObject.indices = this.toNumberArray(this.getIndices());
  29449. return serializationObject;
  29450. };
  29451. // Statics
  29452. Geometry.ExtractFromMesh = function (mesh, id) {
  29453. var geometry = mesh._geometry;
  29454. if (!geometry) {
  29455. return null;
  29456. }
  29457. return geometry.copy(id);
  29458. };
  29459. /**
  29460. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29461. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29462. * Be aware Math.random() could cause collisions, but:
  29463. * "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"
  29464. */
  29465. Geometry.RandomId = function () {
  29466. return BABYLON.Tools.RandomId();
  29467. };
  29468. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29469. var scene = mesh.getScene();
  29470. // Geometry
  29471. var geometryId = parsedGeometry.geometryId;
  29472. if (geometryId) {
  29473. var geometry = scene.getGeometryByID(geometryId);
  29474. if (geometry) {
  29475. geometry.applyToMesh(mesh);
  29476. }
  29477. }
  29478. else if (parsedGeometry instanceof ArrayBuffer) {
  29479. var binaryInfo = mesh._binaryInfo;
  29480. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29481. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29482. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29483. }
  29484. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29485. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29486. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29487. }
  29488. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29489. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29490. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29491. }
  29492. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29493. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29494. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29495. }
  29496. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29497. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29498. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29499. }
  29500. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29501. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29502. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29503. }
  29504. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29505. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29506. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29507. }
  29508. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29509. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29510. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29511. }
  29512. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29513. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29514. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29515. }
  29516. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29517. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29518. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29519. }
  29520. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29521. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29522. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29523. }
  29524. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29525. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29526. mesh.setIndices(indicesData);
  29527. }
  29528. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29529. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29530. mesh.subMeshes = [];
  29531. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29532. var materialIndex = subMeshesData[(i * 5) + 0];
  29533. var verticesStart = subMeshesData[(i * 5) + 1];
  29534. var verticesCount = subMeshesData[(i * 5) + 2];
  29535. var indexStart = subMeshesData[(i * 5) + 3];
  29536. var indexCount = subMeshesData[(i * 5) + 4];
  29537. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29538. }
  29539. }
  29540. }
  29541. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29542. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29543. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29544. if (parsedGeometry.uvs) {
  29545. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29546. }
  29547. if (parsedGeometry.uvs2) {
  29548. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29549. }
  29550. if (parsedGeometry.uvs3) {
  29551. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29552. }
  29553. if (parsedGeometry.uvs4) {
  29554. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29555. }
  29556. if (parsedGeometry.uvs5) {
  29557. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29558. }
  29559. if (parsedGeometry.uvs6) {
  29560. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29561. }
  29562. if (parsedGeometry.colors) {
  29563. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29564. }
  29565. if (parsedGeometry.matricesIndices) {
  29566. if (!parsedGeometry.matricesIndices._isExpanded) {
  29567. var floatIndices = [];
  29568. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29569. var matricesIndex = parsedGeometry.matricesIndices[i];
  29570. floatIndices.push(matricesIndex & 0x000000FF);
  29571. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29572. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29573. floatIndices.push(matricesIndex >> 24);
  29574. }
  29575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29576. }
  29577. else {
  29578. delete parsedGeometry.matricesIndices._isExpanded;
  29579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29580. }
  29581. }
  29582. if (parsedGeometry.matricesIndicesExtra) {
  29583. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29584. var floatIndices = [];
  29585. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29586. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29587. floatIndices.push(matricesIndex & 0x000000FF);
  29588. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29589. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29590. floatIndices.push(matricesIndex >> 24);
  29591. }
  29592. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29593. }
  29594. else {
  29595. delete parsedGeometry.matricesIndices._isExpanded;
  29596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29597. }
  29598. }
  29599. if (parsedGeometry.matricesWeights) {
  29600. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29601. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29602. }
  29603. if (parsedGeometry.matricesWeightsExtra) {
  29604. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29606. }
  29607. mesh.setIndices(parsedGeometry.indices);
  29608. }
  29609. // SubMeshes
  29610. if (parsedGeometry.subMeshes) {
  29611. mesh.subMeshes = [];
  29612. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29613. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29614. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29615. }
  29616. }
  29617. // Flat shading
  29618. if (mesh._shouldGenerateFlatShading) {
  29619. mesh.convertToFlatShadedMesh();
  29620. delete mesh._shouldGenerateFlatShading;
  29621. }
  29622. // Update
  29623. mesh.computeWorldMatrix(true);
  29624. // Octree
  29625. if (scene['_selectionOctree']) {
  29626. scene['_selectionOctree'].addMesh(mesh);
  29627. }
  29628. };
  29629. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29630. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29631. return;
  29632. }
  29633. var size = matricesWeights.length;
  29634. for (var i = 0; i < size; i += influencers) {
  29635. var weight = 0;
  29636. var biggerIndex = i;
  29637. var biggerWeight = 0;
  29638. for (var j = 0; j < influencers - 1; j++) {
  29639. weight += matricesWeights[i + j];
  29640. if (matricesWeights[i + j] > biggerWeight) {
  29641. biggerWeight = matricesWeights[i + j];
  29642. biggerIndex = i + j;
  29643. }
  29644. }
  29645. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29646. }
  29647. };
  29648. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29649. if (scene.getGeometryByID(parsedVertexData.id)) {
  29650. return null; // null since geometry could be something else than a box...
  29651. }
  29652. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29653. if (BABYLON.Tags) {
  29654. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29655. }
  29656. if (parsedVertexData.delayLoadingFile) {
  29657. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29658. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29659. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29660. geometry._delayInfo = [];
  29661. if (parsedVertexData.hasUVs) {
  29662. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29663. }
  29664. if (parsedVertexData.hasUVs2) {
  29665. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29666. }
  29667. if (parsedVertexData.hasUVs3) {
  29668. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29669. }
  29670. if (parsedVertexData.hasUVs4) {
  29671. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29672. }
  29673. if (parsedVertexData.hasUVs5) {
  29674. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29675. }
  29676. if (parsedVertexData.hasUVs6) {
  29677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29678. }
  29679. if (parsedVertexData.hasColors) {
  29680. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29681. }
  29682. if (parsedVertexData.hasMatricesIndices) {
  29683. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29684. }
  29685. if (parsedVertexData.hasMatricesWeights) {
  29686. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29687. }
  29688. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29689. }
  29690. else {
  29691. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29692. }
  29693. scene.pushGeometry(geometry, true);
  29694. return geometry;
  29695. };
  29696. return Geometry;
  29697. }());
  29698. BABYLON.Geometry = Geometry;
  29699. /////// Primitives //////////////////////////////////////////////
  29700. (function (Geometry) {
  29701. var Primitives;
  29702. (function (Primitives) {
  29703. /// Abstract class
  29704. var _Primitive = (function (_super) {
  29705. __extends(_Primitive, _super);
  29706. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29707. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29708. _this._canBeRegenerated = _canBeRegenerated;
  29709. _this._beingRegenerated = true;
  29710. _this.regenerate();
  29711. _this._beingRegenerated = false;
  29712. return _this;
  29713. }
  29714. _Primitive.prototype.canBeRegenerated = function () {
  29715. return this._canBeRegenerated;
  29716. };
  29717. _Primitive.prototype.regenerate = function () {
  29718. if (!this._canBeRegenerated) {
  29719. return;
  29720. }
  29721. this._beingRegenerated = true;
  29722. this.setAllVerticesData(this._regenerateVertexData(), false);
  29723. this._beingRegenerated = false;
  29724. };
  29725. _Primitive.prototype.asNewGeometry = function (id) {
  29726. return _super.prototype.copy.call(this, id);
  29727. };
  29728. // overrides
  29729. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29730. if (!this._beingRegenerated) {
  29731. return;
  29732. }
  29733. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29734. };
  29735. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29736. if (!this._beingRegenerated) {
  29737. return;
  29738. }
  29739. _super.prototype.setVerticesData.call(this, kind, data, false);
  29740. };
  29741. // to override
  29742. // protected
  29743. _Primitive.prototype._regenerateVertexData = function () {
  29744. throw new Error("Abstract method");
  29745. };
  29746. _Primitive.prototype.copy = function (id) {
  29747. throw new Error("Must be overriden in sub-classes.");
  29748. };
  29749. _Primitive.prototype.serialize = function () {
  29750. var serializationObject = _super.prototype.serialize.call(this);
  29751. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29752. return serializationObject;
  29753. };
  29754. return _Primitive;
  29755. }(Geometry));
  29756. Primitives._Primitive = _Primitive;
  29757. var Ribbon = (function (_super) {
  29758. __extends(Ribbon, _super);
  29759. // Members
  29760. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29763. _this.pathArray = pathArray;
  29764. _this.closeArray = closeArray;
  29765. _this.closePath = closePath;
  29766. _this.offset = offset;
  29767. _this.side = side;
  29768. return _this;
  29769. }
  29770. Ribbon.prototype._regenerateVertexData = function () {
  29771. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29772. };
  29773. Ribbon.prototype.copy = function (id) {
  29774. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29775. };
  29776. return Ribbon;
  29777. }(_Primitive));
  29778. Primitives.Ribbon = Ribbon;
  29779. var Box = (function (_super) {
  29780. __extends(Box, _super);
  29781. // Members
  29782. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29783. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29784. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29785. _this.size = size;
  29786. _this.side = side;
  29787. return _this;
  29788. }
  29789. Box.prototype._regenerateVertexData = function () {
  29790. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29791. };
  29792. Box.prototype.copy = function (id) {
  29793. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29794. };
  29795. Box.prototype.serialize = function () {
  29796. var serializationObject = _super.prototype.serialize.call(this);
  29797. serializationObject.size = this.size;
  29798. return serializationObject;
  29799. };
  29800. Box.Parse = function (parsedBox, scene) {
  29801. if (scene.getGeometryByID(parsedBox.id)) {
  29802. return null; // null since geometry could be something else than a box...
  29803. }
  29804. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29805. if (BABYLON.Tags) {
  29806. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29807. }
  29808. scene.pushGeometry(box, true);
  29809. return box;
  29810. };
  29811. return Box;
  29812. }(_Primitive));
  29813. Primitives.Box = Box;
  29814. var Sphere = (function (_super) {
  29815. __extends(Sphere, _super);
  29816. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29819. _this.segments = segments;
  29820. _this.diameter = diameter;
  29821. _this.side = side;
  29822. return _this;
  29823. }
  29824. Sphere.prototype._regenerateVertexData = function () {
  29825. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29826. };
  29827. Sphere.prototype.copy = function (id) {
  29828. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29829. };
  29830. Sphere.prototype.serialize = function () {
  29831. var serializationObject = _super.prototype.serialize.call(this);
  29832. serializationObject.segments = this.segments;
  29833. serializationObject.diameter = this.diameter;
  29834. return serializationObject;
  29835. };
  29836. Sphere.Parse = function (parsedSphere, scene) {
  29837. if (scene.getGeometryByID(parsedSphere.id)) {
  29838. return null; // null since geometry could be something else than a sphere...
  29839. }
  29840. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29841. if (BABYLON.Tags) {
  29842. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29843. }
  29844. scene.pushGeometry(sphere, true);
  29845. return sphere;
  29846. };
  29847. return Sphere;
  29848. }(_Primitive));
  29849. Primitives.Sphere = Sphere;
  29850. var Disc = (function (_super) {
  29851. __extends(Disc, _super);
  29852. // Members
  29853. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29854. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29855. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29856. _this.radius = radius;
  29857. _this.tessellation = tessellation;
  29858. _this.side = side;
  29859. return _this;
  29860. }
  29861. Disc.prototype._regenerateVertexData = function () {
  29862. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29863. };
  29864. Disc.prototype.copy = function (id) {
  29865. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29866. };
  29867. return Disc;
  29868. }(_Primitive));
  29869. Primitives.Disc = Disc;
  29870. var Cylinder = (function (_super) {
  29871. __extends(Cylinder, _super);
  29872. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29873. if (subdivisions === void 0) { subdivisions = 1; }
  29874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29875. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29876. _this.height = height;
  29877. _this.diameterTop = diameterTop;
  29878. _this.diameterBottom = diameterBottom;
  29879. _this.tessellation = tessellation;
  29880. _this.subdivisions = subdivisions;
  29881. _this.side = side;
  29882. return _this;
  29883. }
  29884. Cylinder.prototype._regenerateVertexData = function () {
  29885. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29886. };
  29887. Cylinder.prototype.copy = function (id) {
  29888. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29889. };
  29890. Cylinder.prototype.serialize = function () {
  29891. var serializationObject = _super.prototype.serialize.call(this);
  29892. serializationObject.height = this.height;
  29893. serializationObject.diameterTop = this.diameterTop;
  29894. serializationObject.diameterBottom = this.diameterBottom;
  29895. serializationObject.tessellation = this.tessellation;
  29896. return serializationObject;
  29897. };
  29898. Cylinder.Parse = function (parsedCylinder, scene) {
  29899. if (scene.getGeometryByID(parsedCylinder.id)) {
  29900. return null; // null since geometry could be something else than a cylinder...
  29901. }
  29902. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29903. if (BABYLON.Tags) {
  29904. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29905. }
  29906. scene.pushGeometry(cylinder, true);
  29907. return cylinder;
  29908. };
  29909. return Cylinder;
  29910. }(_Primitive));
  29911. Primitives.Cylinder = Cylinder;
  29912. var Torus = (function (_super) {
  29913. __extends(Torus, _super);
  29914. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29915. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29916. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29917. _this.diameter = diameter;
  29918. _this.thickness = thickness;
  29919. _this.tessellation = tessellation;
  29920. _this.side = side;
  29921. return _this;
  29922. }
  29923. Torus.prototype._regenerateVertexData = function () {
  29924. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29925. };
  29926. Torus.prototype.copy = function (id) {
  29927. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29928. };
  29929. Torus.prototype.serialize = function () {
  29930. var serializationObject = _super.prototype.serialize.call(this);
  29931. serializationObject.diameter = this.diameter;
  29932. serializationObject.thickness = this.thickness;
  29933. serializationObject.tessellation = this.tessellation;
  29934. return serializationObject;
  29935. };
  29936. Torus.Parse = function (parsedTorus, scene) {
  29937. if (scene.getGeometryByID(parsedTorus.id)) {
  29938. return null; // null since geometry could be something else than a torus...
  29939. }
  29940. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29941. if (BABYLON.Tags) {
  29942. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29943. }
  29944. scene.pushGeometry(torus, true);
  29945. return torus;
  29946. };
  29947. return Torus;
  29948. }(_Primitive));
  29949. Primitives.Torus = Torus;
  29950. var Ground = (function (_super) {
  29951. __extends(Ground, _super);
  29952. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29953. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29954. _this.width = width;
  29955. _this.height = height;
  29956. _this.subdivisions = subdivisions;
  29957. return _this;
  29958. }
  29959. Ground.prototype._regenerateVertexData = function () {
  29960. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29961. };
  29962. Ground.prototype.copy = function (id) {
  29963. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29964. };
  29965. Ground.prototype.serialize = function () {
  29966. var serializationObject = _super.prototype.serialize.call(this);
  29967. serializationObject.width = this.width;
  29968. serializationObject.height = this.height;
  29969. serializationObject.subdivisions = this.subdivisions;
  29970. return serializationObject;
  29971. };
  29972. Ground.Parse = function (parsedGround, scene) {
  29973. if (scene.getGeometryByID(parsedGround.id)) {
  29974. return null; // null since geometry could be something else than a ground...
  29975. }
  29976. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29977. if (BABYLON.Tags) {
  29978. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29979. }
  29980. scene.pushGeometry(ground, true);
  29981. return ground;
  29982. };
  29983. return Ground;
  29984. }(_Primitive));
  29985. Primitives.Ground = Ground;
  29986. var TiledGround = (function (_super) {
  29987. __extends(TiledGround, _super);
  29988. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29989. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29990. _this.xmin = xmin;
  29991. _this.zmin = zmin;
  29992. _this.xmax = xmax;
  29993. _this.zmax = zmax;
  29994. _this.subdivisions = subdivisions;
  29995. _this.precision = precision;
  29996. return _this;
  29997. }
  29998. TiledGround.prototype._regenerateVertexData = function () {
  29999. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30000. };
  30001. TiledGround.prototype.copy = function (id) {
  30002. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30003. };
  30004. return TiledGround;
  30005. }(_Primitive));
  30006. Primitives.TiledGround = TiledGround;
  30007. var Plane = (function (_super) {
  30008. __extends(Plane, _super);
  30009. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30010. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30011. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30012. _this.size = size;
  30013. _this.side = side;
  30014. return _this;
  30015. }
  30016. Plane.prototype._regenerateVertexData = function () {
  30017. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30018. };
  30019. Plane.prototype.copy = function (id) {
  30020. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30021. };
  30022. Plane.prototype.serialize = function () {
  30023. var serializationObject = _super.prototype.serialize.call(this);
  30024. serializationObject.size = this.size;
  30025. return serializationObject;
  30026. };
  30027. Plane.Parse = function (parsedPlane, scene) {
  30028. if (scene.getGeometryByID(parsedPlane.id)) {
  30029. return null; // null since geometry could be something else than a ground...
  30030. }
  30031. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30032. if (BABYLON.Tags) {
  30033. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30034. }
  30035. scene.pushGeometry(plane, true);
  30036. return plane;
  30037. };
  30038. return Plane;
  30039. }(_Primitive));
  30040. Primitives.Plane = Plane;
  30041. var TorusKnot = (function (_super) {
  30042. __extends(TorusKnot, _super);
  30043. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30044. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30045. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30046. _this.radius = radius;
  30047. _this.tube = tube;
  30048. _this.radialSegments = radialSegments;
  30049. _this.tubularSegments = tubularSegments;
  30050. _this.p = p;
  30051. _this.q = q;
  30052. _this.side = side;
  30053. return _this;
  30054. }
  30055. TorusKnot.prototype._regenerateVertexData = function () {
  30056. 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 });
  30057. };
  30058. TorusKnot.prototype.copy = function (id) {
  30059. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30060. };
  30061. TorusKnot.prototype.serialize = function () {
  30062. var serializationObject = _super.prototype.serialize.call(this);
  30063. serializationObject.radius = this.radius;
  30064. serializationObject.tube = this.tube;
  30065. serializationObject.radialSegments = this.radialSegments;
  30066. serializationObject.tubularSegments = this.tubularSegments;
  30067. serializationObject.p = this.p;
  30068. serializationObject.q = this.q;
  30069. return serializationObject;
  30070. };
  30071. ;
  30072. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30073. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30074. return null; // null since geometry could be something else than a ground...
  30075. }
  30076. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30077. if (BABYLON.Tags) {
  30078. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30079. }
  30080. scene.pushGeometry(torusKnot, true);
  30081. return torusKnot;
  30082. };
  30083. return TorusKnot;
  30084. }(_Primitive));
  30085. Primitives.TorusKnot = TorusKnot;
  30086. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30087. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30088. })(BABYLON || (BABYLON = {}));
  30089. //# sourceMappingURL=babylon.geometry.js.map
  30090. var BABYLON;
  30091. (function (BABYLON) {
  30092. var PostProcessManager = (function () {
  30093. function PostProcessManager(scene) {
  30094. this._vertexBuffers = {};
  30095. this._scene = scene;
  30096. }
  30097. PostProcessManager.prototype._prepareBuffers = function () {
  30098. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30099. return;
  30100. }
  30101. // VBO
  30102. var vertices = [];
  30103. vertices.push(1, 1);
  30104. vertices.push(-1, 1);
  30105. vertices.push(-1, -1);
  30106. vertices.push(1, -1);
  30107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30108. this._buildIndexBuffer();
  30109. };
  30110. PostProcessManager.prototype._buildIndexBuffer = function () {
  30111. // Indices
  30112. var indices = [];
  30113. indices.push(0);
  30114. indices.push(1);
  30115. indices.push(2);
  30116. indices.push(0);
  30117. indices.push(2);
  30118. indices.push(3);
  30119. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30120. };
  30121. PostProcessManager.prototype._rebuild = function () {
  30122. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30123. return;
  30124. }
  30125. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30126. this._buildIndexBuffer();
  30127. };
  30128. // Methods
  30129. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30130. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30131. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30132. return false;
  30133. }
  30134. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30135. return true;
  30136. };
  30137. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30138. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30139. var engine = this._scene.getEngine();
  30140. for (var index = 0; index < postProcesses.length; index++) {
  30141. if (index < postProcesses.length - 1) {
  30142. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30143. }
  30144. else {
  30145. if (targetTexture) {
  30146. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30147. }
  30148. else {
  30149. engine.restoreDefaultFramebuffer();
  30150. }
  30151. }
  30152. var pp = postProcesses[index];
  30153. var effect = pp.apply();
  30154. if (effect) {
  30155. pp.onBeforeRenderObservable.notifyObservers(effect);
  30156. // VBOs
  30157. this._prepareBuffers();
  30158. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30159. // Draw order
  30160. engine.draw(true, 0, 6);
  30161. pp.onAfterRenderObservable.notifyObservers(effect);
  30162. }
  30163. }
  30164. // Restore depth buffer
  30165. engine.setDepthBuffer(true);
  30166. engine.setDepthWrite(true);
  30167. };
  30168. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30169. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30170. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30171. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30172. return;
  30173. }
  30174. var engine = this._scene.getEngine();
  30175. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30176. if (index < len - 1) {
  30177. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30178. }
  30179. else {
  30180. if (targetTexture) {
  30181. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30182. }
  30183. else {
  30184. engine.restoreDefaultFramebuffer();
  30185. }
  30186. }
  30187. if (doNotPresent) {
  30188. break;
  30189. }
  30190. var pp = postProcesses[index];
  30191. var effect = pp.apply();
  30192. if (effect) {
  30193. pp.onBeforeRenderObservable.notifyObservers(effect);
  30194. // VBOs
  30195. this._prepareBuffers();
  30196. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30197. // Draw order
  30198. engine.draw(true, 0, 6);
  30199. pp.onAfterRenderObservable.notifyObservers(effect);
  30200. }
  30201. }
  30202. // Restore states
  30203. engine.setDepthBuffer(true);
  30204. engine.setDepthWrite(true);
  30205. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30206. };
  30207. PostProcessManager.prototype.dispose = function () {
  30208. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30209. if (buffer) {
  30210. buffer.dispose();
  30211. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30212. }
  30213. if (this._indexBuffer) {
  30214. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30215. this._indexBuffer = null;
  30216. }
  30217. };
  30218. return PostProcessManager;
  30219. }());
  30220. BABYLON.PostProcessManager = PostProcessManager;
  30221. })(BABYLON || (BABYLON = {}));
  30222. //# sourceMappingURL=babylon.postProcessManager.js.map
  30223. var BABYLON;
  30224. (function (BABYLON) {
  30225. /**
  30226. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30227. */
  30228. var PerformanceMonitor = (function () {
  30229. /**
  30230. * constructor
  30231. * @param frameSampleSize The number of samples required to saturate the sliding window
  30232. */
  30233. function PerformanceMonitor(frameSampleSize) {
  30234. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30235. this._enabled = true;
  30236. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30237. }
  30238. /**
  30239. * Samples current frame
  30240. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30241. */
  30242. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30243. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30244. if (!this._enabled)
  30245. return;
  30246. if (this._lastFrameTimeMs != null) {
  30247. var dt = timeMs - this._lastFrameTimeMs;
  30248. this._rollingFrameTime.add(dt);
  30249. }
  30250. this._lastFrameTimeMs = timeMs;
  30251. };
  30252. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30253. /**
  30254. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30255. * @return Average frame time in milliseconds
  30256. */
  30257. get: function () {
  30258. return this._rollingFrameTime.average;
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30264. /**
  30265. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30266. * @return Frame time variance in milliseconds squared
  30267. */
  30268. get: function () {
  30269. return this._rollingFrameTime.variance;
  30270. },
  30271. enumerable: true,
  30272. configurable: true
  30273. });
  30274. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30275. /**
  30276. * Returns the frame time of the most recent frame
  30277. * @return Frame time in milliseconds
  30278. */
  30279. get: function () {
  30280. return this._rollingFrameTime.history(0);
  30281. },
  30282. enumerable: true,
  30283. configurable: true
  30284. });
  30285. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30286. /**
  30287. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30288. * @return Framerate in frames per second
  30289. */
  30290. get: function () {
  30291. return 1000.0 / this._rollingFrameTime.average;
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30297. /**
  30298. * Returns the average framerate in frames per second using the most recent frame time
  30299. * @return Framerate in frames per second
  30300. */
  30301. get: function () {
  30302. return 1000.0 / this._rollingFrameTime.history(0);
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30308. /**
  30309. * Returns true if enough samples have been taken to completely fill the sliding window
  30310. * @return true if saturated
  30311. */
  30312. get: function () {
  30313. return this._rollingFrameTime.isSaturated();
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. /**
  30319. * Enables contributions to the sliding window sample set
  30320. */
  30321. PerformanceMonitor.prototype.enable = function () {
  30322. this._enabled = true;
  30323. };
  30324. /**
  30325. * Disables contributions to the sliding window sample set
  30326. * Samples will not be interpolated over the disabled period
  30327. */
  30328. PerformanceMonitor.prototype.disable = function () {
  30329. this._enabled = false;
  30330. //clear last sample to avoid interpolating over the disabled period when next enabled
  30331. this._lastFrameTimeMs = null;
  30332. this._lastChangeTimeMs = null;
  30333. };
  30334. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30335. /**
  30336. * Returns true if sampling is enabled
  30337. * @return true if enabled
  30338. */
  30339. get: function () {
  30340. return this._enabled;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. /**
  30346. * Resets performance monitor
  30347. */
  30348. PerformanceMonitor.prototype.reset = function () {
  30349. //clear last sample to avoid interpolating over the disabled period when next enabled
  30350. this._lastFrameTimeMs = null;
  30351. this._lastChangeTimeMs = null;
  30352. //wipe record
  30353. this._rollingFrameTime.reset();
  30354. };
  30355. return PerformanceMonitor;
  30356. }());
  30357. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30358. /**
  30359. * RollingAverage
  30360. *
  30361. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30362. */
  30363. var RollingAverage = (function () {
  30364. /**
  30365. * constructor
  30366. * @param length The number of samples required to saturate the sliding window
  30367. */
  30368. function RollingAverage(length) {
  30369. this._samples = new Array(length);
  30370. this.reset();
  30371. }
  30372. /**
  30373. * Adds a sample to the sample set
  30374. * @param v The sample value
  30375. */
  30376. RollingAverage.prototype.add = function (v) {
  30377. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30378. var delta;
  30379. //we need to check if we've already wrapped round
  30380. if (this.isSaturated()) {
  30381. //remove bottom of stack from mean
  30382. var bottomValue = this._samples[this._pos];
  30383. delta = bottomValue - this.average;
  30384. this.average -= delta / (this._sampleCount - 1);
  30385. this._m2 -= delta * (bottomValue - this.average);
  30386. }
  30387. else {
  30388. this._sampleCount++;
  30389. }
  30390. //add new value to mean
  30391. delta = v - this.average;
  30392. this.average += delta / (this._sampleCount);
  30393. this._m2 += delta * (v - this.average);
  30394. //set the new variance
  30395. this.variance = this._m2 / (this._sampleCount - 1);
  30396. this._samples[this._pos] = v;
  30397. this._pos++;
  30398. this._pos %= this._samples.length; //positive wrap around
  30399. };
  30400. /**
  30401. * Returns previously added values or null if outside of history or outside the sliding window domain
  30402. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30403. * @return Value previously recorded with add() or null if outside of range
  30404. */
  30405. RollingAverage.prototype.history = function (i) {
  30406. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30407. return null;
  30408. }
  30409. var i0 = this._wrapPosition(this._pos - 1.0);
  30410. return this._samples[this._wrapPosition(i0 - i)];
  30411. };
  30412. /**
  30413. * Returns true if enough samples have been taken to completely fill the sliding window
  30414. * @return true if sample-set saturated
  30415. */
  30416. RollingAverage.prototype.isSaturated = function () {
  30417. return this._sampleCount >= this._samples.length;
  30418. };
  30419. /**
  30420. * Resets the rolling average (equivalent to 0 samples taken so far)
  30421. */
  30422. RollingAverage.prototype.reset = function () {
  30423. this.average = 0;
  30424. this.variance = 0;
  30425. this._sampleCount = 0;
  30426. this._pos = 0;
  30427. this._m2 = 0;
  30428. };
  30429. /**
  30430. * Wraps a value around the sample range boundaries
  30431. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30432. * @return Wrapped position in sample range
  30433. */
  30434. RollingAverage.prototype._wrapPosition = function (i) {
  30435. var max = this._samples.length;
  30436. return ((i % max) + max) % max;
  30437. };
  30438. return RollingAverage;
  30439. }());
  30440. BABYLON.RollingAverage = RollingAverage;
  30441. })(BABYLON || (BABYLON = {}));
  30442. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30443. var BABYLON;
  30444. (function (BABYLON) {
  30445. var StandardMaterialDefines = (function (_super) {
  30446. __extends(StandardMaterialDefines, _super);
  30447. function StandardMaterialDefines() {
  30448. var _this = _super.call(this) || this;
  30449. _this.MAINUV1 = false;
  30450. _this.MAINUV2 = false;
  30451. _this.DIFFUSE = false;
  30452. _this.DIFFUSEDIRECTUV = 0;
  30453. _this.AMBIENT = false;
  30454. _this.AMBIENTDIRECTUV = 0;
  30455. _this.OPACITY = false;
  30456. _this.OPACITYDIRECTUV = 0;
  30457. _this.OPACITYRGB = false;
  30458. _this.REFLECTION = false;
  30459. _this.EMISSIVE = false;
  30460. _this.EMISSIVEDIRECTUV = 0;
  30461. _this.SPECULAR = false;
  30462. _this.SPECULARDIRECTUV = 0;
  30463. _this.BUMP = false;
  30464. _this.BUMPDIRECTUV = 0;
  30465. _this.PARALLAX = false;
  30466. _this.PARALLAXOCCLUSION = false;
  30467. _this.SPECULAROVERALPHA = false;
  30468. _this.CLIPPLANE = false;
  30469. _this.ALPHATEST = false;
  30470. _this.DEPTHPREPASS = false;
  30471. _this.ALPHAFROMDIFFUSE = false;
  30472. _this.POINTSIZE = false;
  30473. _this.FOG = false;
  30474. _this.SPECULARTERM = false;
  30475. _this.DIFFUSEFRESNEL = false;
  30476. _this.OPACITYFRESNEL = false;
  30477. _this.REFLECTIONFRESNEL = false;
  30478. _this.REFRACTIONFRESNEL = false;
  30479. _this.EMISSIVEFRESNEL = false;
  30480. _this.FRESNEL = false;
  30481. _this.NORMAL = false;
  30482. _this.UV1 = false;
  30483. _this.UV2 = false;
  30484. _this.VERTEXCOLOR = false;
  30485. _this.VERTEXALPHA = false;
  30486. _this.NUM_BONE_INFLUENCERS = 0;
  30487. _this.BonesPerMesh = 0;
  30488. _this.INSTANCES = false;
  30489. _this.GLOSSINESS = false;
  30490. _this.ROUGHNESS = false;
  30491. _this.EMISSIVEASILLUMINATION = false;
  30492. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30493. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30494. _this.LIGHTMAP = false;
  30495. _this.LIGHTMAPDIRECTUV = 0;
  30496. _this.USELIGHTMAPASSHADOWMAP = false;
  30497. _this.REFLECTIONMAP_3D = false;
  30498. _this.REFLECTIONMAP_SPHERICAL = false;
  30499. _this.REFLECTIONMAP_PLANAR = false;
  30500. _this.REFLECTIONMAP_CUBIC = false;
  30501. _this.REFLECTIONMAP_PROJECTION = false;
  30502. _this.REFLECTIONMAP_SKYBOX = false;
  30503. _this.REFLECTIONMAP_EXPLICIT = false;
  30504. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30505. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30506. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30507. _this.INVERTCUBICMAP = false;
  30508. _this.LOGARITHMICDEPTH = false;
  30509. _this.REFRACTION = false;
  30510. _this.REFRACTIONMAP_3D = false;
  30511. _this.REFLECTIONOVERALPHA = false;
  30512. _this.TWOSIDEDLIGHTING = false;
  30513. _this.SHADOWFLOAT = false;
  30514. _this.MORPHTARGETS = false;
  30515. _this.MORPHTARGETS_NORMAL = false;
  30516. _this.MORPHTARGETS_TANGENT = false;
  30517. _this.NUM_MORPH_INFLUENCERS = 0;
  30518. _this.USERIGHTHANDEDSYSTEM = false;
  30519. _this.IMAGEPROCESSING = false;
  30520. _this.VIGNETTE = false;
  30521. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30522. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30523. _this.TONEMAPPING = false;
  30524. _this.CONTRAST = false;
  30525. _this.COLORCURVES = false;
  30526. _this.COLORGRADING = false;
  30527. _this.SAMPLER3DGREENDEPTH = false;
  30528. _this.SAMPLER3DBGRMAP = false;
  30529. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30530. _this.EXPOSURE = false;
  30531. _this.rebuild();
  30532. return _this;
  30533. }
  30534. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30535. var modes = [
  30536. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30537. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30538. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30539. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30540. ];
  30541. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30542. var mode = modes_1[_i];
  30543. this[mode] = (mode === modeToEnable);
  30544. }
  30545. };
  30546. return StandardMaterialDefines;
  30547. }(BABYLON.MaterialDefines));
  30548. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30549. var StandardMaterial = (function (_super) {
  30550. __extends(StandardMaterial, _super);
  30551. function StandardMaterial(name, scene) {
  30552. var _this = _super.call(this, name, scene) || this;
  30553. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30554. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30555. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30556. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30557. _this.specularPower = 64;
  30558. _this._useAlphaFromDiffuseTexture = false;
  30559. _this._useEmissiveAsIllumination = false;
  30560. _this._linkEmissiveWithDiffuse = false;
  30561. _this._useSpecularOverAlpha = false;
  30562. _this._useReflectionOverAlpha = false;
  30563. _this._disableLighting = false;
  30564. _this._useParallax = false;
  30565. _this._useParallaxOcclusion = false;
  30566. _this.parallaxScaleBias = 0.05;
  30567. _this._roughness = 0;
  30568. _this.indexOfRefraction = 0.98;
  30569. _this.invertRefractionY = true;
  30570. _this._useLightmapAsShadowmap = false;
  30571. _this._useReflectionFresnelFromSpecular = false;
  30572. _this._useGlossinessFromSpecularMapAlpha = false;
  30573. _this._maxSimultaneousLights = 4;
  30574. /**
  30575. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30576. */
  30577. _this._invertNormalMapX = false;
  30578. /**
  30579. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30580. */
  30581. _this._invertNormalMapY = false;
  30582. /**
  30583. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30584. */
  30585. _this._twoSidedLighting = false;
  30586. _this._renderTargets = new BABYLON.SmartArray(16);
  30587. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30588. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30589. // Setup the default processing configuration to the scene.
  30590. _this._attachImageProcessingConfiguration(null);
  30591. _this.getRenderTargetTextures = function () {
  30592. _this._renderTargets.reset();
  30593. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30594. _this._renderTargets.push(_this._reflectionTexture);
  30595. }
  30596. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30597. _this._renderTargets.push(_this._refractionTexture);
  30598. }
  30599. return _this._renderTargets;
  30600. };
  30601. return _this;
  30602. }
  30603. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30604. /**
  30605. * Gets the image processing configuration used either in this material.
  30606. */
  30607. get: function () {
  30608. return this._imageProcessingConfiguration;
  30609. },
  30610. /**
  30611. * Sets the Default image processing configuration used either in the this material.
  30612. *
  30613. * If sets to null, the scene one is in use.
  30614. */
  30615. set: function (value) {
  30616. this._attachImageProcessingConfiguration(value);
  30617. // Ensure the effect will be rebuilt.
  30618. this._markAllSubMeshesAsTexturesDirty();
  30619. },
  30620. enumerable: true,
  30621. configurable: true
  30622. });
  30623. /**
  30624. * Attaches a new image processing configuration to the Standard Material.
  30625. * @param configuration
  30626. */
  30627. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30628. var _this = this;
  30629. if (configuration === this._imageProcessingConfiguration) {
  30630. return;
  30631. }
  30632. // Detaches observer.
  30633. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30634. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30635. }
  30636. // Pick the scene configuration if needed.
  30637. if (!configuration) {
  30638. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30639. }
  30640. else {
  30641. this._imageProcessingConfiguration = configuration;
  30642. }
  30643. // Attaches observer.
  30644. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30645. _this._markAllSubMeshesAsImageProcessingDirty();
  30646. });
  30647. };
  30648. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30649. /**
  30650. * Gets wether the color curves effect is enabled.
  30651. */
  30652. get: function () {
  30653. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30654. },
  30655. /**
  30656. * Sets wether the color curves effect is enabled.
  30657. */
  30658. set: function (value) {
  30659. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30660. },
  30661. enumerable: true,
  30662. configurable: true
  30663. });
  30664. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30665. /**
  30666. * Gets wether the color grading effect is enabled.
  30667. */
  30668. get: function () {
  30669. return this.imageProcessingConfiguration.colorGradingEnabled;
  30670. },
  30671. /**
  30672. * Gets wether the color grading effect is enabled.
  30673. */
  30674. set: function (value) {
  30675. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30676. },
  30677. enumerable: true,
  30678. configurable: true
  30679. });
  30680. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30681. /**
  30682. * Gets wether tonemapping is enabled or not.
  30683. */
  30684. get: function () {
  30685. return this._imageProcessingConfiguration.toneMappingEnabled;
  30686. },
  30687. /**
  30688. * Sets wether tonemapping is enabled or not
  30689. */
  30690. set: function (value) {
  30691. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30692. },
  30693. enumerable: true,
  30694. configurable: true
  30695. });
  30696. ;
  30697. ;
  30698. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30699. /**
  30700. * The camera exposure used on this material.
  30701. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30702. * This corresponds to a photographic exposure.
  30703. */
  30704. get: function () {
  30705. return this._imageProcessingConfiguration.exposure;
  30706. },
  30707. /**
  30708. * The camera exposure used on this material.
  30709. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30710. * This corresponds to a photographic exposure.
  30711. */
  30712. set: function (value) {
  30713. this._imageProcessingConfiguration.exposure = value;
  30714. },
  30715. enumerable: true,
  30716. configurable: true
  30717. });
  30718. ;
  30719. ;
  30720. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30721. /**
  30722. * Gets The camera contrast used on this material.
  30723. */
  30724. get: function () {
  30725. return this._imageProcessingConfiguration.contrast;
  30726. },
  30727. /**
  30728. * Sets The camera contrast used on this material.
  30729. */
  30730. set: function (value) {
  30731. this._imageProcessingConfiguration.contrast = value;
  30732. },
  30733. enumerable: true,
  30734. configurable: true
  30735. });
  30736. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30737. /**
  30738. * Gets the Color Grading 2D Lookup Texture.
  30739. */
  30740. get: function () {
  30741. return this._imageProcessingConfiguration.colorGradingTexture;
  30742. },
  30743. /**
  30744. * Sets the Color Grading 2D Lookup Texture.
  30745. */
  30746. set: function (value) {
  30747. this._imageProcessingConfiguration.colorGradingTexture = value;
  30748. },
  30749. enumerable: true,
  30750. configurable: true
  30751. });
  30752. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30753. /**
  30754. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30755. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30756. * 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;
  30757. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30758. */
  30759. get: function () {
  30760. return this._imageProcessingConfiguration.colorCurves;
  30761. },
  30762. /**
  30763. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30764. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30765. * 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;
  30766. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30767. */
  30768. set: function (value) {
  30769. this._imageProcessingConfiguration.colorCurves = value;
  30770. },
  30771. enumerable: true,
  30772. configurable: true
  30773. });
  30774. StandardMaterial.prototype.getClassName = function () {
  30775. return "StandardMaterial";
  30776. };
  30777. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30778. get: function () {
  30779. return this._useLogarithmicDepth;
  30780. },
  30781. set: function (value) {
  30782. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30783. this._markAllSubMeshesAsMiscDirty();
  30784. },
  30785. enumerable: true,
  30786. configurable: true
  30787. });
  30788. StandardMaterial.prototype.needAlphaBlending = function () {
  30789. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30790. };
  30791. StandardMaterial.prototype.needAlphaTesting = function () {
  30792. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30793. };
  30794. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30795. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30796. };
  30797. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30798. return this._diffuseTexture;
  30799. };
  30800. /**
  30801. * Child classes can use it to update shaders
  30802. */
  30803. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30804. if (this.isFrozen) {
  30805. if (this._wasPreviouslyReady && subMesh.effect) {
  30806. return true;
  30807. }
  30808. }
  30809. if (!subMesh._materialDefines) {
  30810. subMesh._materialDefines = new StandardMaterialDefines();
  30811. }
  30812. var scene = this.getScene();
  30813. var defines = subMesh._materialDefines;
  30814. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30815. if (defines._renderId === scene.getRenderId()) {
  30816. return true;
  30817. }
  30818. }
  30819. var engine = scene.getEngine();
  30820. // Lights
  30821. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30822. // Textures
  30823. if (defines._areTexturesDirty) {
  30824. defines._needUVs = false;
  30825. defines.MAINUV1 = false;
  30826. defines.MAINUV2 = false;
  30827. if (scene.texturesEnabled) {
  30828. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30829. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30830. return false;
  30831. }
  30832. else {
  30833. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30834. }
  30835. }
  30836. else {
  30837. defines.DIFFUSE = false;
  30838. }
  30839. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30840. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30841. return false;
  30842. }
  30843. else {
  30844. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30845. }
  30846. }
  30847. else {
  30848. defines.AMBIENT = false;
  30849. }
  30850. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30851. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30852. return false;
  30853. }
  30854. else {
  30855. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30856. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30857. }
  30858. }
  30859. else {
  30860. defines.OPACITY = false;
  30861. }
  30862. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30863. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30864. return false;
  30865. }
  30866. else {
  30867. defines._needNormals = true;
  30868. defines.REFLECTION = true;
  30869. defines.ROUGHNESS = (this._roughness > 0);
  30870. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30871. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30872. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30873. switch (this._reflectionTexture.coordinatesMode) {
  30874. case BABYLON.Texture.CUBIC_MODE:
  30875. case BABYLON.Texture.INVCUBIC_MODE:
  30876. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30877. break;
  30878. case BABYLON.Texture.EXPLICIT_MODE:
  30879. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30880. break;
  30881. case BABYLON.Texture.PLANAR_MODE:
  30882. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30883. break;
  30884. case BABYLON.Texture.PROJECTION_MODE:
  30885. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30886. break;
  30887. case BABYLON.Texture.SKYBOX_MODE:
  30888. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30889. break;
  30890. case BABYLON.Texture.SPHERICAL_MODE:
  30891. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30892. break;
  30893. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30894. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30895. break;
  30896. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30897. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30898. break;
  30899. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30900. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30901. break;
  30902. }
  30903. }
  30904. }
  30905. else {
  30906. defines.REFLECTION = false;
  30907. }
  30908. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30909. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30910. return false;
  30911. }
  30912. else {
  30913. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30914. }
  30915. }
  30916. else {
  30917. defines.EMISSIVE = false;
  30918. }
  30919. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30920. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30921. return false;
  30922. }
  30923. else {
  30924. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30925. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30926. }
  30927. }
  30928. else {
  30929. defines.LIGHTMAP = false;
  30930. }
  30931. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30932. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30933. return false;
  30934. }
  30935. else {
  30936. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30937. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30938. }
  30939. }
  30940. else {
  30941. defines.SPECULAR = false;
  30942. }
  30943. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30944. // Bump texure can not be not blocking.
  30945. if (!this._bumpTexture.isReady()) {
  30946. return false;
  30947. }
  30948. else {
  30949. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30950. defines.PARALLAX = this._useParallax;
  30951. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30952. }
  30953. }
  30954. else {
  30955. defines.BUMP = false;
  30956. }
  30957. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30958. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30959. return false;
  30960. }
  30961. else {
  30962. defines._needUVs = true;
  30963. defines.REFRACTION = true;
  30964. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30965. }
  30966. }
  30967. else {
  30968. defines.REFRACTION = false;
  30969. }
  30970. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30971. }
  30972. else {
  30973. defines.DIFFUSE = false;
  30974. defines.AMBIENT = false;
  30975. defines.OPACITY = false;
  30976. defines.REFLECTION = false;
  30977. defines.EMISSIVE = false;
  30978. defines.LIGHTMAP = false;
  30979. defines.BUMP = false;
  30980. defines.REFRACTION = false;
  30981. }
  30982. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30983. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30984. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30985. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30986. }
  30987. if (defines._areImageProcessingDirty) {
  30988. if (!this._imageProcessingConfiguration.isReady()) {
  30989. return false;
  30990. }
  30991. this._imageProcessingConfiguration.prepareDefines(defines);
  30992. }
  30993. if (defines._areFresnelDirty) {
  30994. if (StandardMaterial.FresnelEnabled) {
  30995. // Fresnel
  30996. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30997. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30998. this._reflectionFresnelParameters) {
  30999. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31000. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31001. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31002. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31003. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31004. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31005. defines._needNormals = true;
  31006. defines.FRESNEL = true;
  31007. }
  31008. }
  31009. else {
  31010. defines.FRESNEL = false;
  31011. }
  31012. }
  31013. // Misc.
  31014. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31015. // Attribs
  31016. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  31017. // Values that need to be evaluated on every frame
  31018. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  31019. // Get correct effect
  31020. if (defines.isDirty) {
  31021. defines.markAsProcessed();
  31022. scene.resetCachedMaterial();
  31023. // Fallbacks
  31024. var fallbacks = new BABYLON.EffectFallbacks();
  31025. if (defines.REFLECTION) {
  31026. fallbacks.addFallback(0, "REFLECTION");
  31027. }
  31028. if (defines.SPECULAR) {
  31029. fallbacks.addFallback(0, "SPECULAR");
  31030. }
  31031. if (defines.BUMP) {
  31032. fallbacks.addFallback(0, "BUMP");
  31033. }
  31034. if (defines.PARALLAX) {
  31035. fallbacks.addFallback(1, "PARALLAX");
  31036. }
  31037. if (defines.PARALLAXOCCLUSION) {
  31038. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31039. }
  31040. if (defines.SPECULAROVERALPHA) {
  31041. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31042. }
  31043. if (defines.FOG) {
  31044. fallbacks.addFallback(1, "FOG");
  31045. }
  31046. if (defines.POINTSIZE) {
  31047. fallbacks.addFallback(0, "POINTSIZE");
  31048. }
  31049. if (defines.LOGARITHMICDEPTH) {
  31050. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31051. }
  31052. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31053. if (defines.SPECULARTERM) {
  31054. fallbacks.addFallback(0, "SPECULARTERM");
  31055. }
  31056. if (defines.DIFFUSEFRESNEL) {
  31057. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31058. }
  31059. if (defines.OPACITYFRESNEL) {
  31060. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31061. }
  31062. if (defines.REFLECTIONFRESNEL) {
  31063. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31064. }
  31065. if (defines.EMISSIVEFRESNEL) {
  31066. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31067. }
  31068. if (defines.FRESNEL) {
  31069. fallbacks.addFallback(4, "FRESNEL");
  31070. }
  31071. //Attributes
  31072. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31073. if (defines.NORMAL) {
  31074. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31075. }
  31076. if (defines.UV1) {
  31077. attribs.push(BABYLON.VertexBuffer.UVKind);
  31078. }
  31079. if (defines.UV2) {
  31080. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31081. }
  31082. if (defines.VERTEXCOLOR) {
  31083. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31084. }
  31085. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31086. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31087. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31088. var shaderName = "default";
  31089. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31090. "vFogInfos", "vFogColor", "pointSize",
  31091. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31092. "mBones",
  31093. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31094. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31095. "logarithmicDepthConstant", "vNormalReoderParams"
  31096. ];
  31097. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31098. var uniformBuffers = ["Material", "Scene"];
  31099. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31100. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31101. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31102. uniformsNames: uniforms,
  31103. uniformBuffersNames: uniformBuffers,
  31104. samplers: samplers,
  31105. defines: defines,
  31106. maxSimultaneousLights: this._maxSimultaneousLights
  31107. });
  31108. if (this.customShaderNameResolve) {
  31109. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  31110. }
  31111. var join = defines.toString();
  31112. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  31113. attributes: attribs,
  31114. uniformsNames: uniforms,
  31115. uniformBuffersNames: uniformBuffers,
  31116. samplers: samplers,
  31117. defines: join,
  31118. fallbacks: fallbacks,
  31119. onCompiled: this.onCompiled,
  31120. onError: this.onError,
  31121. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31122. }, engine), defines);
  31123. this.buildUniformLayout();
  31124. }
  31125. if (!subMesh.effect.isReady()) {
  31126. return false;
  31127. }
  31128. defines._renderId = scene.getRenderId();
  31129. this._wasPreviouslyReady = true;
  31130. return true;
  31131. };
  31132. StandardMaterial.prototype.buildUniformLayout = function () {
  31133. // Order is important !
  31134. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31135. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31136. this._uniformBuffer.addUniform("opacityParts", 4);
  31137. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31138. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31139. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31140. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31141. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31142. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31143. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31144. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31145. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31146. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31147. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31148. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31149. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31150. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31151. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31152. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31153. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31154. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31155. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31156. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31157. this._uniformBuffer.addUniform("specularMatrix", 16);
  31158. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31159. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31160. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31161. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31162. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31163. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31164. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31165. this._uniformBuffer.addUniform("pointSize", 1);
  31166. this._uniformBuffer.create();
  31167. };
  31168. StandardMaterial.prototype.unbind = function () {
  31169. if (this._activeEffect) {
  31170. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31171. this._activeEffect.setTexture("reflection2DSampler", null);
  31172. }
  31173. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31174. this._activeEffect.setTexture("refraction2DSampler", null);
  31175. }
  31176. }
  31177. _super.prototype.unbind.call(this);
  31178. };
  31179. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31180. var scene = this.getScene();
  31181. var defines = subMesh._materialDefines;
  31182. if (!defines) {
  31183. return;
  31184. }
  31185. var effect = subMesh.effect;
  31186. this._activeEffect = effect;
  31187. // Matrices
  31188. this.bindOnlyWorldMatrix(world);
  31189. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31190. // Bones
  31191. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31192. if (mustRebind) {
  31193. this._uniformBuffer.bindToEffect(effect, "Material");
  31194. this.bindViewProjection(effect);
  31195. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31196. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31197. // Fresnel
  31198. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31199. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31200. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31201. }
  31202. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31203. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31204. }
  31205. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31206. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31207. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31208. }
  31209. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31210. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31211. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31212. }
  31213. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31214. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31215. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31216. }
  31217. }
  31218. // Textures
  31219. if (scene.texturesEnabled) {
  31220. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31221. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31222. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31223. }
  31224. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31225. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31226. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31227. }
  31228. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31229. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31230. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31231. }
  31232. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31233. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31234. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31235. }
  31236. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31237. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31238. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31239. }
  31240. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31241. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31242. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31243. }
  31244. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31245. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31246. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31247. }
  31248. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31249. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31250. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31251. if (scene._mirroredCameraPosition) {
  31252. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 0 : 1.0, this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 0 : 1.0, this.invertNormalMapY ? 1.0 : -1.0);
  31253. }
  31254. else {
  31255. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 1.0 : 0, this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? 1.0 : 0, this.invertNormalMapY ? -1.0 : 1.0);
  31256. }
  31257. }
  31258. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31259. var depth = 1.0;
  31260. if (!this._refractionTexture.isCube) {
  31261. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31262. if (this._refractionTexture.depth) {
  31263. depth = this._refractionTexture.depth;
  31264. }
  31265. }
  31266. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31267. }
  31268. }
  31269. // Point size
  31270. if (this.pointsCloud) {
  31271. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31272. }
  31273. if (defines.SPECULARTERM) {
  31274. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31275. }
  31276. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31277. // Diffuse
  31278. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31279. }
  31280. // Textures
  31281. if (scene.texturesEnabled) {
  31282. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31283. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31284. }
  31285. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31286. effect.setTexture("ambientSampler", this._ambientTexture);
  31287. }
  31288. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31289. effect.setTexture("opacitySampler", this._opacityTexture);
  31290. }
  31291. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31292. if (this._reflectionTexture.isCube) {
  31293. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31294. }
  31295. else {
  31296. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31297. }
  31298. }
  31299. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31300. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31301. }
  31302. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31303. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31304. }
  31305. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31306. effect.setTexture("specularSampler", this._specularTexture);
  31307. }
  31308. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31309. effect.setTexture("bumpSampler", this._bumpTexture);
  31310. }
  31311. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31312. var depth = 1.0;
  31313. if (this._refractionTexture.isCube) {
  31314. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31315. }
  31316. else {
  31317. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31318. }
  31319. }
  31320. }
  31321. // Clip plane
  31322. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31323. // Colors
  31324. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31325. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31326. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31327. }
  31328. if (mustRebind || !this.isFrozen) {
  31329. // Lights
  31330. if (scene.lightsEnabled && !this._disableLighting) {
  31331. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31332. }
  31333. // View
  31334. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31335. this.bindView(effect);
  31336. }
  31337. // Fog
  31338. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31339. // Morph targets
  31340. if (defines.NUM_MORPH_INFLUENCERS) {
  31341. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31342. }
  31343. // Log. depth
  31344. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31345. // image processing
  31346. this._imageProcessingConfiguration.bind(this._activeEffect);
  31347. }
  31348. this._uniformBuffer.update();
  31349. this._afterBind(mesh, this._activeEffect);
  31350. };
  31351. StandardMaterial.prototype.getAnimatables = function () {
  31352. var results = [];
  31353. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31354. results.push(this._diffuseTexture);
  31355. }
  31356. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31357. results.push(this._ambientTexture);
  31358. }
  31359. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31360. results.push(this._opacityTexture);
  31361. }
  31362. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31363. results.push(this._reflectionTexture);
  31364. }
  31365. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31366. results.push(this._emissiveTexture);
  31367. }
  31368. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31369. results.push(this._specularTexture);
  31370. }
  31371. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31372. results.push(this._bumpTexture);
  31373. }
  31374. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31375. results.push(this._lightmapTexture);
  31376. }
  31377. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31378. results.push(this._refractionTexture);
  31379. }
  31380. return results;
  31381. };
  31382. StandardMaterial.prototype.getActiveTextures = function () {
  31383. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31384. if (this._diffuseTexture) {
  31385. activeTextures.push(this._diffuseTexture);
  31386. }
  31387. if (this._ambientTexture) {
  31388. activeTextures.push(this._ambientTexture);
  31389. }
  31390. if (this._opacityTexture) {
  31391. activeTextures.push(this._opacityTexture);
  31392. }
  31393. if (this._reflectionTexture) {
  31394. activeTextures.push(this._reflectionTexture);
  31395. }
  31396. if (this._emissiveTexture) {
  31397. activeTextures.push(this._emissiveTexture);
  31398. }
  31399. if (this._specularTexture) {
  31400. activeTextures.push(this._specularTexture);
  31401. }
  31402. if (this._bumpTexture) {
  31403. activeTextures.push(this._bumpTexture);
  31404. }
  31405. if (this._lightmapTexture) {
  31406. activeTextures.push(this._lightmapTexture);
  31407. }
  31408. if (this._refractionTexture) {
  31409. activeTextures.push(this._refractionTexture);
  31410. }
  31411. return activeTextures;
  31412. };
  31413. StandardMaterial.prototype.hasTexture = function (texture) {
  31414. if (_super.prototype.hasTexture.call(this, texture)) {
  31415. return true;
  31416. }
  31417. if (this._diffuseTexture === texture) {
  31418. return true;
  31419. }
  31420. if (this._ambientTexture === texture) {
  31421. return true;
  31422. }
  31423. if (this._opacityTexture === texture) {
  31424. return true;
  31425. }
  31426. if (this._reflectionTexture === texture) {
  31427. return true;
  31428. }
  31429. if (this._emissiveTexture === texture) {
  31430. return true;
  31431. }
  31432. if (this._specularTexture === texture) {
  31433. return true;
  31434. }
  31435. if (this._bumpTexture === texture) {
  31436. return true;
  31437. }
  31438. if (this._lightmapTexture === texture) {
  31439. return true;
  31440. }
  31441. if (this._refractionTexture === texture) {
  31442. return true;
  31443. }
  31444. return false;
  31445. };
  31446. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31447. if (forceDisposeTextures) {
  31448. if (this._diffuseTexture) {
  31449. this._diffuseTexture.dispose();
  31450. }
  31451. if (this._ambientTexture) {
  31452. this._ambientTexture.dispose();
  31453. }
  31454. if (this._opacityTexture) {
  31455. this._opacityTexture.dispose();
  31456. }
  31457. if (this._reflectionTexture) {
  31458. this._reflectionTexture.dispose();
  31459. }
  31460. if (this._emissiveTexture) {
  31461. this._emissiveTexture.dispose();
  31462. }
  31463. if (this._specularTexture) {
  31464. this._specularTexture.dispose();
  31465. }
  31466. if (this._bumpTexture) {
  31467. this._bumpTexture.dispose();
  31468. }
  31469. if (this._lightmapTexture) {
  31470. this._lightmapTexture.dispose();
  31471. }
  31472. if (this._refractionTexture) {
  31473. this._refractionTexture.dispose();
  31474. }
  31475. }
  31476. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31477. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31478. }
  31479. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31480. };
  31481. StandardMaterial.prototype.clone = function (name) {
  31482. var _this = this;
  31483. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31484. result.name = name;
  31485. result.id = name;
  31486. return result;
  31487. };
  31488. StandardMaterial.prototype.serialize = function () {
  31489. return BABYLON.SerializationHelper.Serialize(this);
  31490. };
  31491. // Statics
  31492. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31493. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31494. };
  31495. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31496. get: function () {
  31497. return StandardMaterial._DiffuseTextureEnabled;
  31498. },
  31499. set: function (value) {
  31500. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31501. return;
  31502. }
  31503. StandardMaterial._DiffuseTextureEnabled = value;
  31504. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31505. },
  31506. enumerable: true,
  31507. configurable: true
  31508. });
  31509. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31510. get: function () {
  31511. return StandardMaterial._AmbientTextureEnabled;
  31512. },
  31513. set: function (value) {
  31514. if (StandardMaterial._AmbientTextureEnabled === value) {
  31515. return;
  31516. }
  31517. StandardMaterial._AmbientTextureEnabled = value;
  31518. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31519. },
  31520. enumerable: true,
  31521. configurable: true
  31522. });
  31523. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31524. get: function () {
  31525. return StandardMaterial._OpacityTextureEnabled;
  31526. },
  31527. set: function (value) {
  31528. if (StandardMaterial._OpacityTextureEnabled === value) {
  31529. return;
  31530. }
  31531. StandardMaterial._OpacityTextureEnabled = value;
  31532. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31533. },
  31534. enumerable: true,
  31535. configurable: true
  31536. });
  31537. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31538. get: function () {
  31539. return StandardMaterial._ReflectionTextureEnabled;
  31540. },
  31541. set: function (value) {
  31542. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31543. return;
  31544. }
  31545. StandardMaterial._ReflectionTextureEnabled = value;
  31546. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31552. get: function () {
  31553. return StandardMaterial._EmissiveTextureEnabled;
  31554. },
  31555. set: function (value) {
  31556. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31557. return;
  31558. }
  31559. StandardMaterial._EmissiveTextureEnabled = value;
  31560. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31561. },
  31562. enumerable: true,
  31563. configurable: true
  31564. });
  31565. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31566. get: function () {
  31567. return StandardMaterial._SpecularTextureEnabled;
  31568. },
  31569. set: function (value) {
  31570. if (StandardMaterial._SpecularTextureEnabled === value) {
  31571. return;
  31572. }
  31573. StandardMaterial._SpecularTextureEnabled = value;
  31574. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31575. },
  31576. enumerable: true,
  31577. configurable: true
  31578. });
  31579. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31580. get: function () {
  31581. return StandardMaterial._BumpTextureEnabled;
  31582. },
  31583. set: function (value) {
  31584. if (StandardMaterial._BumpTextureEnabled === value) {
  31585. return;
  31586. }
  31587. StandardMaterial._BumpTextureEnabled = value;
  31588. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31589. },
  31590. enumerable: true,
  31591. configurable: true
  31592. });
  31593. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31594. get: function () {
  31595. return StandardMaterial._LightmapTextureEnabled;
  31596. },
  31597. set: function (value) {
  31598. if (StandardMaterial._LightmapTextureEnabled === value) {
  31599. return;
  31600. }
  31601. StandardMaterial._LightmapTextureEnabled = value;
  31602. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31603. },
  31604. enumerable: true,
  31605. configurable: true
  31606. });
  31607. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31608. get: function () {
  31609. return StandardMaterial._RefractionTextureEnabled;
  31610. },
  31611. set: function (value) {
  31612. if (StandardMaterial._RefractionTextureEnabled === value) {
  31613. return;
  31614. }
  31615. StandardMaterial._RefractionTextureEnabled = value;
  31616. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31617. },
  31618. enumerable: true,
  31619. configurable: true
  31620. });
  31621. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31622. get: function () {
  31623. return StandardMaterial._ColorGradingTextureEnabled;
  31624. },
  31625. set: function (value) {
  31626. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31627. return;
  31628. }
  31629. StandardMaterial._ColorGradingTextureEnabled = value;
  31630. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31631. },
  31632. enumerable: true,
  31633. configurable: true
  31634. });
  31635. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31636. get: function () {
  31637. return StandardMaterial._FresnelEnabled;
  31638. },
  31639. set: function (value) {
  31640. if (StandardMaterial._FresnelEnabled === value) {
  31641. return;
  31642. }
  31643. StandardMaterial._FresnelEnabled = value;
  31644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31645. },
  31646. enumerable: true,
  31647. configurable: true
  31648. });
  31649. // Flags used to enable or disable a type of texture for all Standard Materials
  31650. StandardMaterial._DiffuseTextureEnabled = true;
  31651. StandardMaterial._AmbientTextureEnabled = true;
  31652. StandardMaterial._OpacityTextureEnabled = true;
  31653. StandardMaterial._ReflectionTextureEnabled = true;
  31654. StandardMaterial._EmissiveTextureEnabled = true;
  31655. StandardMaterial._SpecularTextureEnabled = true;
  31656. StandardMaterial._BumpTextureEnabled = true;
  31657. StandardMaterial._LightmapTextureEnabled = true;
  31658. StandardMaterial._RefractionTextureEnabled = true;
  31659. StandardMaterial._ColorGradingTextureEnabled = true;
  31660. StandardMaterial._FresnelEnabled = true;
  31661. __decorate([
  31662. BABYLON.serializeAsTexture("diffuseTexture")
  31663. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31664. __decorate([
  31665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31666. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31667. __decorate([
  31668. BABYLON.serializeAsTexture("ambientTexture")
  31669. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31670. __decorate([
  31671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31672. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31673. __decorate([
  31674. BABYLON.serializeAsTexture("opacityTexture")
  31675. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31676. __decorate([
  31677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31678. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31679. __decorate([
  31680. BABYLON.serializeAsTexture("reflectionTexture")
  31681. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31682. __decorate([
  31683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31684. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31685. __decorate([
  31686. BABYLON.serializeAsTexture("emissiveTexture")
  31687. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31688. __decorate([
  31689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31690. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31691. __decorate([
  31692. BABYLON.serializeAsTexture("specularTexture")
  31693. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31694. __decorate([
  31695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31696. ], StandardMaterial.prototype, "specularTexture", void 0);
  31697. __decorate([
  31698. BABYLON.serializeAsTexture("bumpTexture")
  31699. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31700. __decorate([
  31701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31702. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31703. __decorate([
  31704. BABYLON.serializeAsTexture("lightmapTexture")
  31705. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31706. __decorate([
  31707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31708. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31709. __decorate([
  31710. BABYLON.serializeAsTexture("refractionTexture")
  31711. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31712. __decorate([
  31713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31714. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31715. __decorate([
  31716. BABYLON.serializeAsColor3("ambient")
  31717. ], StandardMaterial.prototype, "ambientColor", void 0);
  31718. __decorate([
  31719. BABYLON.serializeAsColor3("diffuse")
  31720. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31721. __decorate([
  31722. BABYLON.serializeAsColor3("specular")
  31723. ], StandardMaterial.prototype, "specularColor", void 0);
  31724. __decorate([
  31725. BABYLON.serializeAsColor3("emissive")
  31726. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], StandardMaterial.prototype, "specularPower", void 0);
  31730. __decorate([
  31731. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31732. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31733. __decorate([
  31734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31735. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31736. __decorate([
  31737. BABYLON.serialize("useEmissiveAsIllumination")
  31738. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31739. __decorate([
  31740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31741. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31742. __decorate([
  31743. BABYLON.serialize("linkEmissiveWithDiffuse")
  31744. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31745. __decorate([
  31746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31747. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31748. __decorate([
  31749. BABYLON.serialize("useSpecularOverAlpha")
  31750. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31751. __decorate([
  31752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31753. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31754. __decorate([
  31755. BABYLON.serialize("useReflectionOverAlpha")
  31756. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31757. __decorate([
  31758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31759. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31760. __decorate([
  31761. BABYLON.serialize("disableLighting")
  31762. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31763. __decorate([
  31764. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31765. ], StandardMaterial.prototype, "disableLighting", void 0);
  31766. __decorate([
  31767. BABYLON.serialize("useParallax")
  31768. ], StandardMaterial.prototype, "_useParallax", void 0);
  31769. __decorate([
  31770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31771. ], StandardMaterial.prototype, "useParallax", void 0);
  31772. __decorate([
  31773. BABYLON.serialize("useParallaxOcclusion")
  31774. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31775. __decorate([
  31776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31777. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31778. __decorate([
  31779. BABYLON.serialize()
  31780. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31781. __decorate([
  31782. BABYLON.serialize("roughness")
  31783. ], StandardMaterial.prototype, "_roughness", void 0);
  31784. __decorate([
  31785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31786. ], StandardMaterial.prototype, "roughness", void 0);
  31787. __decorate([
  31788. BABYLON.serialize()
  31789. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31790. __decorate([
  31791. BABYLON.serialize()
  31792. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31793. __decorate([
  31794. BABYLON.serialize("useLightmapAsShadowmap")
  31795. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31796. __decorate([
  31797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31798. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31799. __decorate([
  31800. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31801. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31802. __decorate([
  31803. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31804. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31805. __decorate([
  31806. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31807. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31808. __decorate([
  31809. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31810. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31811. __decorate([
  31812. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31813. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31814. __decorate([
  31815. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31816. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31817. __decorate([
  31818. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31819. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31820. __decorate([
  31821. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31822. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31823. __decorate([
  31824. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31825. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31826. __decorate([
  31827. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31828. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31829. __decorate([
  31830. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31831. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31832. __decorate([
  31833. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31834. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31835. __decorate([
  31836. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31837. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31838. __decorate([
  31839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31840. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31841. __decorate([
  31842. BABYLON.serialize("maxSimultaneousLights")
  31843. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31844. __decorate([
  31845. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31846. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31847. __decorate([
  31848. BABYLON.serialize("invertNormalMapX")
  31849. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31850. __decorate([
  31851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31852. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31853. __decorate([
  31854. BABYLON.serialize("invertNormalMapY")
  31855. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31856. __decorate([
  31857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31858. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31859. __decorate([
  31860. BABYLON.serialize("twoSidedLighting")
  31861. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31862. __decorate([
  31863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31864. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31865. __decorate([
  31866. BABYLON.serialize()
  31867. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31868. return StandardMaterial;
  31869. }(BABYLON.PushMaterial));
  31870. BABYLON.StandardMaterial = StandardMaterial;
  31871. })(BABYLON || (BABYLON = {}));
  31872. //# sourceMappingURL=babylon.standardMaterial.js.map
  31873. var BABYLON;
  31874. (function (BABYLON) {
  31875. var PBRMaterialDefines = (function (_super) {
  31876. __extends(PBRMaterialDefines, _super);
  31877. function PBRMaterialDefines() {
  31878. var _this = _super.call(this) || this;
  31879. _this.PBR = true;
  31880. _this.MAINUV1 = false;
  31881. _this.MAINUV2 = false;
  31882. _this.UV1 = false;
  31883. _this.UV2 = false;
  31884. _this.ALBEDO = false;
  31885. _this.ALBEDODIRECTUV = 0;
  31886. _this.VERTEXCOLOR = false;
  31887. _this.AMBIENT = false;
  31888. _this.AMBIENTDIRECTUV = 0;
  31889. _this.AMBIENTINGRAYSCALE = false;
  31890. _this.OPACITY = false;
  31891. _this.VERTEXALPHA = false;
  31892. _this.OPACITYDIRECTUV = 0;
  31893. _this.OPACITYRGB = false;
  31894. _this.ALPHATEST = false;
  31895. _this.DEPTHPREPASS = false;
  31896. _this.ALPHABLEND = false;
  31897. _this.ALPHAFROMALBEDO = false;
  31898. _this.ALPHATESTVALUE = 0.5;
  31899. _this.SPECULAROVERALPHA = false;
  31900. _this.RADIANCEOVERALPHA = false;
  31901. _this.ALPHAFRESNEL = false;
  31902. _this.PREMULTIPLYALPHA = false;
  31903. _this.EMISSIVE = false;
  31904. _this.EMISSIVEDIRECTUV = 0;
  31905. _this.REFLECTIVITY = false;
  31906. _this.REFLECTIVITYDIRECTUV = 0;
  31907. _this.SPECULARTERM = false;
  31908. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31909. _this.MICROSURFACEAUTOMATIC = false;
  31910. _this.LODBASEDMICROSFURACE = false;
  31911. _this.MICROSURFACEMAP = false;
  31912. _this.MICROSURFACEMAPDIRECTUV = 0;
  31913. _this.METALLICWORKFLOW = false;
  31914. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31915. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31916. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31917. _this.AOSTOREINMETALMAPRED = false;
  31918. _this.ENVIRONMENTBRDF = false;
  31919. _this.NORMAL = false;
  31920. _this.TANGENT = false;
  31921. _this.BUMP = false;
  31922. _this.BUMPDIRECTUV = 0;
  31923. _this.PARALLAX = false;
  31924. _this.PARALLAXOCCLUSION = false;
  31925. _this.NORMALXYSCALE = true;
  31926. _this.LIGHTMAP = false;
  31927. _this.LIGHTMAPDIRECTUV = 0;
  31928. _this.USELIGHTMAPASSHADOWMAP = false;
  31929. _this.REFLECTION = false;
  31930. _this.REFLECTIONMAP_3D = false;
  31931. _this.REFLECTIONMAP_SPHERICAL = false;
  31932. _this.REFLECTIONMAP_PLANAR = false;
  31933. _this.REFLECTIONMAP_CUBIC = false;
  31934. _this.REFLECTIONMAP_PROJECTION = false;
  31935. _this.REFLECTIONMAP_SKYBOX = false;
  31936. _this.REFLECTIONMAP_EXPLICIT = false;
  31937. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31938. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31939. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31940. _this.INVERTCUBICMAP = false;
  31941. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31942. _this.USESPHERICALINFRAGMENT = false;
  31943. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31944. _this.LODINREFLECTIONALPHA = false;
  31945. _this.GAMMAREFLECTION = false;
  31946. _this.REFRACTION = false;
  31947. _this.REFRACTIONMAP_3D = false;
  31948. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31949. _this.LODINREFRACTIONALPHA = false;
  31950. _this.GAMMAREFRACTION = false;
  31951. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31952. _this.INSTANCES = false;
  31953. _this.NUM_BONE_INFLUENCERS = 0;
  31954. _this.BonesPerMesh = 0;
  31955. _this.MORPHTARGETS = false;
  31956. _this.MORPHTARGETS_NORMAL = false;
  31957. _this.MORPHTARGETS_TANGENT = false;
  31958. _this.NUM_MORPH_INFLUENCERS = 0;
  31959. _this.IMAGEPROCESSING = false;
  31960. _this.VIGNETTE = false;
  31961. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31962. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31963. _this.TONEMAPPING = false;
  31964. _this.CONTRAST = false;
  31965. _this.COLORCURVES = false;
  31966. _this.COLORGRADING = false;
  31967. _this.SAMPLER3DGREENDEPTH = false;
  31968. _this.SAMPLER3DBGRMAP = false;
  31969. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31970. _this.EXPOSURE = false;
  31971. _this.USEPHYSICALLIGHTFALLOFF = false;
  31972. _this.TWOSIDEDLIGHTING = false;
  31973. _this.SHADOWFLOAT = false;
  31974. _this.USERIGHTHANDEDSYSTEM = false;
  31975. _this.CLIPPLANE = false;
  31976. _this.POINTSIZE = false;
  31977. _this.FOG = false;
  31978. _this.LOGARITHMICDEPTH = false;
  31979. _this.FORCENORMALFORWARD = false;
  31980. _this.rebuild();
  31981. return _this;
  31982. }
  31983. PBRMaterialDefines.prototype.reset = function () {
  31984. _super.prototype.reset.call(this);
  31985. this.ALPHATESTVALUE = 0.5;
  31986. this.PBR = true;
  31987. };
  31988. return PBRMaterialDefines;
  31989. }(BABYLON.MaterialDefines));
  31990. /**
  31991. * The Physically based material base class of BJS.
  31992. *
  31993. * This offers the main features of a standard PBR material.
  31994. * For more information, please refer to the documentation :
  31995. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31996. */
  31997. var PBRBaseMaterial = (function (_super) {
  31998. __extends(PBRBaseMaterial, _super);
  31999. /**
  32000. * Instantiates a new PBRMaterial instance.
  32001. *
  32002. * @param name The material name
  32003. * @param scene The scene the material will be use in.
  32004. */
  32005. function PBRBaseMaterial(name, scene) {
  32006. var _this = _super.call(this, name, scene) || this;
  32007. /**
  32008. * Intensity of the direct lights e.g. the four lights available in your scene.
  32009. * This impacts both the direct diffuse and specular highlights.
  32010. */
  32011. _this._directIntensity = 1.0;
  32012. /**
  32013. * Intensity of the emissive part of the material.
  32014. * This helps controlling the emissive effect without modifying the emissive color.
  32015. */
  32016. _this._emissiveIntensity = 1.0;
  32017. /**
  32018. * Intensity of the environment e.g. how much the environment will light the object
  32019. * either through harmonics for rough material or through the refelction for shiny ones.
  32020. */
  32021. _this._environmentIntensity = 1.0;
  32022. /**
  32023. * This is a special control allowing the reduction of the specular highlights coming from the
  32024. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32025. */
  32026. _this._specularIntensity = 1.0;
  32027. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  32028. /**
  32029. * Debug Control allowing disabling the bump map on this material.
  32030. */
  32031. _this._disableBumpMap = false;
  32032. /**
  32033. * AKA Occlusion Texture Intensity in other nomenclature.
  32034. */
  32035. _this._ambientTextureStrength = 1.0;
  32036. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  32037. /**
  32038. * AKA Diffuse Color in other nomenclature.
  32039. */
  32040. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  32041. /**
  32042. * AKA Specular Color in other nomenclature.
  32043. */
  32044. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32045. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  32046. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  32047. /**
  32048. * AKA Glossiness in other nomenclature.
  32049. */
  32050. _this._microSurface = 0.9;
  32051. /**
  32052. * source material index of refraction (IOR)' / 'destination material IOR.
  32053. */
  32054. _this._indexOfRefraction = 0.66;
  32055. /**
  32056. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32057. */
  32058. _this._invertRefractionY = false;
  32059. /**
  32060. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32061. * Materials half opaque for instance using refraction could benefit from this control.
  32062. */
  32063. _this._linkRefractionWithTransparency = false;
  32064. _this._useLightmapAsShadowmap = false;
  32065. /**
  32066. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32067. */
  32068. _this._useAlphaFromAlbedoTexture = false;
  32069. /**
  32070. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32071. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32072. */
  32073. _this._useSpecularOverAlpha = true;
  32074. /**
  32075. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32076. */
  32077. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  32078. /**
  32079. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32080. */
  32081. _this._useRoughnessFromMetallicTextureAlpha = true;
  32082. /**
  32083. * Specifies if the metallic texture contains the roughness information in its green channel.
  32084. */
  32085. _this._useRoughnessFromMetallicTextureGreen = false;
  32086. /**
  32087. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32088. */
  32089. _this._useMetallnessFromMetallicTextureBlue = false;
  32090. /**
  32091. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32092. */
  32093. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  32094. /**
  32095. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32096. */
  32097. _this._useAmbientInGrayScale = false;
  32098. /**
  32099. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32100. * The material will try to infer what glossiness each pixel should be.
  32101. */
  32102. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  32103. /**
  32104. * BJS is using an harcoded light falloff based on a manually sets up range.
  32105. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32106. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32107. */
  32108. _this._usePhysicalLightFalloff = true;
  32109. /**
  32110. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32111. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32112. */
  32113. _this._useRadianceOverAlpha = true;
  32114. /**
  32115. * Allows using the bump map in parallax mode.
  32116. */
  32117. _this._useParallax = false;
  32118. /**
  32119. * Allows using the bump map in parallax occlusion mode.
  32120. */
  32121. _this._useParallaxOcclusion = false;
  32122. /**
  32123. * Controls the scale bias of the parallax mode.
  32124. */
  32125. _this._parallaxScaleBias = 0.05;
  32126. /**
  32127. * If sets to true, disables all the lights affecting the material.
  32128. */
  32129. _this._disableLighting = false;
  32130. /**
  32131. * Number of Simultaneous lights allowed on the material.
  32132. */
  32133. _this._maxSimultaneousLights = 4;
  32134. /**
  32135. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32136. */
  32137. _this._invertNormalMapX = false;
  32138. /**
  32139. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32140. */
  32141. _this._invertNormalMapY = false;
  32142. /**
  32143. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32144. */
  32145. _this._twoSidedLighting = false;
  32146. /**
  32147. * Defines the alpha limits in alpha test mode.
  32148. */
  32149. _this._alphaCutOff = 0.4;
  32150. /**
  32151. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32152. */
  32153. _this._forceAlphaTest = false;
  32154. /**
  32155. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32156. * in your scene composition.
  32157. */
  32158. _this._preMultiplyAlpha = false;
  32159. /**
  32160. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32161. * And/Or occlude the blended part.
  32162. */
  32163. _this._useAlphaFresnel = false;
  32164. /**
  32165. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32166. * from cos thetav and roughness:
  32167. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32168. */
  32169. _this._environmentBRDFTexture = null;
  32170. /**
  32171. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32172. */
  32173. _this._forceIrradianceInFragment = false;
  32174. /**
  32175. * Force normal to face away from face.
  32176. * (Temporary internal fix to remove before 3.1)
  32177. */
  32178. _this._forceNormalForward = false;
  32179. _this._renderTargets = new BABYLON.SmartArray(16);
  32180. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32181. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32182. _this._tempColor = new BABYLON.Color3();
  32183. // Setup the default processing configuration to the scene.
  32184. _this._attachImageProcessingConfiguration(null);
  32185. _this.getRenderTargetTextures = function () {
  32186. _this._renderTargets.reset();
  32187. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32188. _this._renderTargets.push(_this._reflectionTexture);
  32189. }
  32190. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32191. _this._renderTargets.push(_this._refractionTexture);
  32192. }
  32193. return _this._renderTargets;
  32194. };
  32195. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32196. return _this;
  32197. }
  32198. /**
  32199. * Attaches a new image processing configuration to the PBR Material.
  32200. * @param configuration
  32201. */
  32202. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32203. var _this = this;
  32204. if (configuration === this._imageProcessingConfiguration) {
  32205. return;
  32206. }
  32207. // Detaches observer.
  32208. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32209. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32210. }
  32211. // Pick the scene configuration if needed.
  32212. if (!configuration) {
  32213. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32214. }
  32215. else {
  32216. this._imageProcessingConfiguration = configuration;
  32217. }
  32218. // Attaches observer.
  32219. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32220. _this._markAllSubMeshesAsImageProcessingDirty();
  32221. });
  32222. };
  32223. PBRBaseMaterial.prototype.getClassName = function () {
  32224. return "PBRBaseMaterial";
  32225. };
  32226. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32227. get: function () {
  32228. return this._useLogarithmicDepth;
  32229. },
  32230. set: function (value) {
  32231. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32232. },
  32233. enumerable: true,
  32234. configurable: true
  32235. });
  32236. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32237. if (this._linkRefractionWithTransparency) {
  32238. return false;
  32239. }
  32240. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32241. };
  32242. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32243. if (this._forceAlphaTest) {
  32244. return true;
  32245. }
  32246. if (this._linkRefractionWithTransparency) {
  32247. return false;
  32248. }
  32249. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32250. };
  32251. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32252. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32253. };
  32254. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32255. return this._albedoTexture;
  32256. };
  32257. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32258. if (this.isFrozen) {
  32259. if (this._wasPreviouslyReady) {
  32260. return true;
  32261. }
  32262. }
  32263. if (!subMesh._materialDefines) {
  32264. subMesh._materialDefines = new PBRMaterialDefines();
  32265. }
  32266. var scene = this.getScene();
  32267. var defines = subMesh._materialDefines;
  32268. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32269. if (defines._renderId === scene.getRenderId()) {
  32270. return true;
  32271. }
  32272. }
  32273. var engine = scene.getEngine();
  32274. // Lights
  32275. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32276. defines._needNormals = true;
  32277. // Textures
  32278. if (defines._areTexturesDirty) {
  32279. defines._needUVs = false;
  32280. if (scene.texturesEnabled) {
  32281. if (scene.getEngine().getCaps().textureLOD) {
  32282. defines.LODBASEDMICROSFURACE = true;
  32283. }
  32284. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32285. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32286. return false;
  32287. }
  32288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32289. }
  32290. else {
  32291. defines.ALBEDO = false;
  32292. }
  32293. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32294. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32295. return false;
  32296. }
  32297. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32298. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32299. }
  32300. else {
  32301. defines.AMBIENT = false;
  32302. }
  32303. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32304. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32305. return false;
  32306. }
  32307. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32308. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32309. }
  32310. else {
  32311. defines.OPACITY = false;
  32312. }
  32313. var reflectionTexture = this._getReflectionTexture();
  32314. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32315. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32316. return false;
  32317. }
  32318. defines.REFLECTION = true;
  32319. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32320. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32321. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32322. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32323. defines.INVERTCUBICMAP = true;
  32324. }
  32325. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32326. switch (reflectionTexture.coordinatesMode) {
  32327. case BABYLON.Texture.CUBIC_MODE:
  32328. case BABYLON.Texture.INVCUBIC_MODE:
  32329. defines.REFLECTIONMAP_CUBIC = true;
  32330. break;
  32331. case BABYLON.Texture.EXPLICIT_MODE:
  32332. defines.REFLECTIONMAP_EXPLICIT = true;
  32333. break;
  32334. case BABYLON.Texture.PLANAR_MODE:
  32335. defines.REFLECTIONMAP_PLANAR = true;
  32336. break;
  32337. case BABYLON.Texture.PROJECTION_MODE:
  32338. defines.REFLECTIONMAP_PROJECTION = true;
  32339. break;
  32340. case BABYLON.Texture.SKYBOX_MODE:
  32341. defines.REFLECTIONMAP_SKYBOX = true;
  32342. break;
  32343. case BABYLON.Texture.SPHERICAL_MODE:
  32344. defines.REFLECTIONMAP_SPHERICAL = true;
  32345. break;
  32346. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32347. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32348. break;
  32349. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32350. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32351. break;
  32352. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32353. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32354. break;
  32355. }
  32356. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32357. if (reflectionTexture.sphericalPolynomial) {
  32358. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32359. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32360. defines.USESPHERICALINFRAGMENT = true;
  32361. }
  32362. }
  32363. }
  32364. }
  32365. else {
  32366. defines.REFLECTION = false;
  32367. defines.REFLECTIONMAP_3D = false;
  32368. defines.REFLECTIONMAP_SPHERICAL = false;
  32369. defines.REFLECTIONMAP_PLANAR = false;
  32370. defines.REFLECTIONMAP_CUBIC = false;
  32371. defines.REFLECTIONMAP_PROJECTION = false;
  32372. defines.REFLECTIONMAP_SKYBOX = false;
  32373. defines.REFLECTIONMAP_EXPLICIT = false;
  32374. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32375. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32376. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32377. defines.INVERTCUBICMAP = false;
  32378. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32379. defines.USESPHERICALINFRAGMENT = false;
  32380. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32381. defines.LODINREFLECTIONALPHA = false;
  32382. defines.GAMMAREFLECTION = false;
  32383. }
  32384. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32385. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32386. return false;
  32387. }
  32388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32389. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32390. }
  32391. else {
  32392. defines.LIGHTMAP = false;
  32393. }
  32394. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32395. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32396. return false;
  32397. }
  32398. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32399. }
  32400. else {
  32401. defines.EMISSIVE = false;
  32402. }
  32403. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32404. if (this._metallicTexture) {
  32405. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32406. return false;
  32407. }
  32408. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32409. defines.METALLICWORKFLOW = true;
  32410. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32411. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32412. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32413. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32414. }
  32415. else if (this._reflectivityTexture) {
  32416. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32417. return false;
  32418. }
  32419. defines.METALLICWORKFLOW = false;
  32420. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32421. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32422. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32423. }
  32424. else {
  32425. defines.METALLICWORKFLOW = false;
  32426. defines.REFLECTIVITY = false;
  32427. }
  32428. if (this._microSurfaceTexture) {
  32429. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32430. return false;
  32431. }
  32432. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32433. }
  32434. else {
  32435. defines.MICROSURFACEMAP = false;
  32436. }
  32437. }
  32438. else {
  32439. defines.REFLECTIVITY = false;
  32440. defines.MICROSURFACEMAP = false;
  32441. }
  32442. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32443. // Bump texure can not be none blocking.
  32444. if (!this._bumpTexture.isReady()) {
  32445. return false;
  32446. }
  32447. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32448. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32449. defines.PARALLAX = true;
  32450. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32451. }
  32452. else {
  32453. defines.PARALLAX = false;
  32454. }
  32455. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32456. }
  32457. else {
  32458. defines.BUMP = false;
  32459. }
  32460. var refractionTexture = this._getRefractionTexture();
  32461. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32462. if (!refractionTexture.isReadyOrNotBlocking()) {
  32463. return false;
  32464. }
  32465. defines.REFRACTION = true;
  32466. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32467. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32468. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32469. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32470. if (this._linkRefractionWithTransparency) {
  32471. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32472. }
  32473. }
  32474. else {
  32475. defines.REFRACTION = false;
  32476. }
  32477. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32478. // This is blocking.
  32479. if (!this._environmentBRDFTexture.isReady()) {
  32480. return false;
  32481. }
  32482. defines.ENVIRONMENTBRDF = true;
  32483. }
  32484. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32485. defines.ALPHAFROMALBEDO = true;
  32486. }
  32487. }
  32488. if (this._useSpecularOverAlpha) {
  32489. defines.SPECULAROVERALPHA = true;
  32490. }
  32491. if (this._usePhysicalLightFalloff) {
  32492. defines.USEPHYSICALLIGHTFALLOFF = true;
  32493. }
  32494. if (this._useRadianceOverAlpha) {
  32495. defines.RADIANCEOVERALPHA = true;
  32496. }
  32497. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32498. defines.METALLICWORKFLOW = true;
  32499. }
  32500. if (!this.backFaceCulling && this._twoSidedLighting) {
  32501. defines.TWOSIDEDLIGHTING = true;
  32502. }
  32503. defines.ALPHATESTVALUE = this._alphaCutOff;
  32504. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32505. defines.ALPHABLEND = this.needAlphaBlending();
  32506. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32507. }
  32508. if (defines._areImageProcessingDirty) {
  32509. if (!this._imageProcessingConfiguration.isReady()) {
  32510. return false;
  32511. }
  32512. this._imageProcessingConfiguration.prepareDefines(defines);
  32513. }
  32514. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32515. // Misc.
  32516. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32517. // Values that need to be evaluated on every frame
  32518. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32519. // Attribs
  32520. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32521. if (mesh) {
  32522. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32523. mesh.createNormals(true);
  32524. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32525. }
  32526. }
  32527. }
  32528. // Get correct effect
  32529. if (defines.isDirty) {
  32530. defines.markAsProcessed();
  32531. scene.resetCachedMaterial();
  32532. // Fallbacks
  32533. var fallbacks = new BABYLON.EffectFallbacks();
  32534. if (defines.ENVIRONMENTBRDF) {
  32535. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32536. }
  32537. if (defines.REFLECTION) {
  32538. fallbacks.addFallback(0, "REFLECTION");
  32539. }
  32540. if (defines.REFRACTION) {
  32541. fallbacks.addFallback(0, "REFRACTION");
  32542. }
  32543. if (defines.REFLECTIVITY) {
  32544. fallbacks.addFallback(0, "REFLECTIVITY");
  32545. }
  32546. if (defines.BUMP) {
  32547. fallbacks.addFallback(0, "BUMP");
  32548. }
  32549. if (defines.PARALLAX) {
  32550. fallbacks.addFallback(1, "PARALLAX");
  32551. }
  32552. if (defines.PARALLAXOCCLUSION) {
  32553. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32554. }
  32555. if (defines.SPECULAROVERALPHA) {
  32556. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32557. }
  32558. if (defines.FOG) {
  32559. fallbacks.addFallback(1, "FOG");
  32560. }
  32561. if (defines.POINTSIZE) {
  32562. fallbacks.addFallback(0, "POINTSIZE");
  32563. }
  32564. if (defines.LOGARITHMICDEPTH) {
  32565. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32566. }
  32567. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32568. if (defines.SPECULARTERM) {
  32569. fallbacks.addFallback(0, "SPECULARTERM");
  32570. }
  32571. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32572. fallbacks.addCPUSkinningFallback(0, mesh);
  32573. }
  32574. //Attributes
  32575. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32576. if (defines.NORMAL) {
  32577. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32578. }
  32579. if (defines.TANGENT) {
  32580. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32581. }
  32582. if (defines.UV1) {
  32583. attribs.push(BABYLON.VertexBuffer.UVKind);
  32584. }
  32585. if (defines.UV2) {
  32586. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32587. }
  32588. if (defines.VERTEXCOLOR) {
  32589. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32590. }
  32591. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32592. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32593. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32594. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32595. "vFogInfos", "vFogColor", "pointSize",
  32596. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32597. "mBones",
  32598. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32599. "vLightingIntensity",
  32600. "logarithmicDepthConstant",
  32601. "vSphericalX", "vSphericalY", "vSphericalZ",
  32602. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32603. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32604. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32605. "vNormalReoderParams"
  32606. ];
  32607. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32608. "bumpSampler", "lightmapSampler", "opacitySampler",
  32609. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32610. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32611. "microSurfaceSampler", "environmentBrdfSampler"];
  32612. var uniformBuffers = ["Material", "Scene"];
  32613. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32614. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32615. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32616. uniformsNames: uniforms,
  32617. uniformBuffersNames: uniformBuffers,
  32618. samplers: samplers,
  32619. defines: defines,
  32620. maxSimultaneousLights: this._maxSimultaneousLights
  32621. });
  32622. var onCompiled = function (effect) {
  32623. if (this.onCompiled) {
  32624. this.onCompiled(effect);
  32625. }
  32626. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32627. }.bind(this);
  32628. var join = defines.toString();
  32629. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32630. attributes: attribs,
  32631. uniformsNames: uniforms,
  32632. uniformBuffersNames: uniformBuffers,
  32633. samplers: samplers,
  32634. defines: join,
  32635. fallbacks: fallbacks,
  32636. onCompiled: onCompiled,
  32637. onError: this.onError,
  32638. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32639. }, engine), defines);
  32640. this.buildUniformLayout();
  32641. }
  32642. if (!subMesh.effect.isReady()) {
  32643. return false;
  32644. }
  32645. defines._renderId = scene.getRenderId();
  32646. this._wasPreviouslyReady = true;
  32647. return true;
  32648. };
  32649. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32650. // Order is important !
  32651. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32652. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32653. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32654. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32655. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32656. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32657. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32658. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32659. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32660. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32661. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32662. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32663. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32664. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32665. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32666. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32667. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32668. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32669. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32670. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32671. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32672. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32673. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32674. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32675. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32676. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32677. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32678. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32679. this._uniformBuffer.addUniform("pointSize", 1);
  32680. this._uniformBuffer.create();
  32681. };
  32682. PBRBaseMaterial.prototype.unbind = function () {
  32683. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32684. this._uniformBuffer.setTexture("reflectionSampler", null);
  32685. }
  32686. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32687. this._uniformBuffer.setTexture("refractionSampler", null);
  32688. }
  32689. _super.prototype.unbind.call(this);
  32690. };
  32691. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32692. this._activeEffect.setMatrix("world", world);
  32693. };
  32694. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32695. var scene = this.getScene();
  32696. var defines = subMesh._materialDefines;
  32697. if (!defines) {
  32698. return;
  32699. }
  32700. var effect = subMesh.effect;
  32701. this._activeEffect = effect;
  32702. // Matrices
  32703. this.bindOnlyWorldMatrix(world);
  32704. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32705. // Bones
  32706. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32707. if (mustRebind) {
  32708. this._uniformBuffer.bindToEffect(effect, "Material");
  32709. this.bindViewProjection(effect);
  32710. var reflectionTexture = this._getReflectionTexture();
  32711. var refractionTexture = this._getRefractionTexture();
  32712. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32713. // Texture uniforms
  32714. if (scene.texturesEnabled) {
  32715. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32716. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32717. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32718. }
  32719. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32720. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32721. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32722. }
  32723. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32724. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32725. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32726. }
  32727. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32728. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32729. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32730. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32731. var polynomials = reflectionTexture.sphericalPolynomial;
  32732. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32733. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32734. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32735. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32736. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32737. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32738. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32739. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32740. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32741. }
  32742. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32743. }
  32744. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32745. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32746. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32747. }
  32748. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32749. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32750. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32751. }
  32752. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32753. if (this._metallicTexture) {
  32754. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32755. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32756. }
  32757. else if (this._reflectivityTexture) {
  32758. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32759. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32760. }
  32761. if (this._microSurfaceTexture) {
  32762. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32763. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32764. }
  32765. }
  32766. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32767. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32768. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32769. if (scene._mirroredCameraPosition) {
  32770. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 0 : 1.0, this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 0 : 1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32771. }
  32772. else {
  32773. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 1.0 : 0, this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? 1.0 : 0, this._invertNormalMapY ? -1.0 : 1.0);
  32774. }
  32775. }
  32776. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32777. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32778. var depth = 1.0;
  32779. if (!refractionTexture.isCube) {
  32780. if (refractionTexture.depth) {
  32781. depth = refractionTexture.depth;
  32782. }
  32783. }
  32784. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32785. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32786. }
  32787. }
  32788. // Point size
  32789. if (this.pointsCloud) {
  32790. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32791. }
  32792. // Colors
  32793. if (defines.METALLICWORKFLOW) {
  32794. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32795. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32796. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32797. }
  32798. else {
  32799. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32800. }
  32801. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32802. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32803. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32804. // Misc
  32805. this._lightingInfos.x = this._directIntensity;
  32806. this._lightingInfos.y = this._emissiveIntensity;
  32807. this._lightingInfos.z = this._environmentIntensity;
  32808. this._lightingInfos.w = this._specularIntensity;
  32809. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32810. }
  32811. // Textures
  32812. if (scene.texturesEnabled) {
  32813. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32814. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32815. }
  32816. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32817. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32818. }
  32819. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32820. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32821. }
  32822. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32823. if (defines.LODBASEDMICROSFURACE) {
  32824. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32825. }
  32826. else {
  32827. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32828. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32829. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32830. }
  32831. }
  32832. if (defines.ENVIRONMENTBRDF) {
  32833. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32834. }
  32835. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32836. if (defines.LODBASEDMICROSFURACE) {
  32837. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32838. }
  32839. else {
  32840. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32841. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32842. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32843. }
  32844. }
  32845. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32846. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32847. }
  32848. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32849. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32850. }
  32851. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32852. if (this._metallicTexture) {
  32853. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32854. }
  32855. else if (this._reflectivityTexture) {
  32856. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32857. }
  32858. if (this._microSurfaceTexture) {
  32859. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32860. }
  32861. }
  32862. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32863. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32864. }
  32865. }
  32866. // Clip plane
  32867. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32868. // Colors
  32869. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32870. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32871. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32872. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32873. }
  32874. if (mustRebind || !this.isFrozen) {
  32875. // Lights
  32876. if (scene.lightsEnabled && !this._disableLighting) {
  32877. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32878. }
  32879. // View
  32880. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32881. this.bindView(effect);
  32882. }
  32883. // Fog
  32884. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32885. // Morph targets
  32886. if (defines.NUM_MORPH_INFLUENCERS) {
  32887. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32888. }
  32889. // image processing
  32890. this._imageProcessingConfiguration.bind(this._activeEffect);
  32891. // Log. depth
  32892. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32893. }
  32894. this._uniformBuffer.update();
  32895. this._afterBind(mesh);
  32896. scene = null;
  32897. };
  32898. PBRBaseMaterial.prototype.getAnimatables = function () {
  32899. var results = [];
  32900. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32901. results.push(this._albedoTexture);
  32902. }
  32903. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32904. results.push(this._ambientTexture);
  32905. }
  32906. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32907. results.push(this._opacityTexture);
  32908. }
  32909. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32910. results.push(this._reflectionTexture);
  32911. }
  32912. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32913. results.push(this._emissiveTexture);
  32914. }
  32915. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32916. results.push(this._metallicTexture);
  32917. }
  32918. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32919. results.push(this._reflectivityTexture);
  32920. }
  32921. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32922. results.push(this._bumpTexture);
  32923. }
  32924. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32925. results.push(this._lightmapTexture);
  32926. }
  32927. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32928. results.push(this._refractionTexture);
  32929. }
  32930. return results;
  32931. };
  32932. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32933. if (this._reflectionTexture) {
  32934. return this._reflectionTexture;
  32935. }
  32936. return this.getScene().environmentTexture;
  32937. };
  32938. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32939. if (this._refractionTexture) {
  32940. return this._refractionTexture;
  32941. }
  32942. if (this._linkRefractionWithTransparency) {
  32943. return this.getScene().environmentTexture;
  32944. }
  32945. return null;
  32946. };
  32947. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32948. if (forceDisposeTextures) {
  32949. if (this._albedoTexture) {
  32950. this._albedoTexture.dispose();
  32951. }
  32952. if (this._ambientTexture) {
  32953. this._ambientTexture.dispose();
  32954. }
  32955. if (this._opacityTexture) {
  32956. this._opacityTexture.dispose();
  32957. }
  32958. if (this._reflectionTexture) {
  32959. this._reflectionTexture.dispose();
  32960. }
  32961. if (this._environmentBRDFTexture) {
  32962. this._environmentBRDFTexture.dispose();
  32963. }
  32964. if (this._emissiveTexture) {
  32965. this._emissiveTexture.dispose();
  32966. }
  32967. if (this._metallicTexture) {
  32968. this._metallicTexture.dispose();
  32969. }
  32970. if (this._reflectivityTexture) {
  32971. this._reflectivityTexture.dispose();
  32972. }
  32973. if (this._bumpTexture) {
  32974. this._bumpTexture.dispose();
  32975. }
  32976. if (this._lightmapTexture) {
  32977. this._lightmapTexture.dispose();
  32978. }
  32979. if (this._refractionTexture) {
  32980. this._refractionTexture.dispose();
  32981. }
  32982. }
  32983. this._renderTargets.dispose();
  32984. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32985. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32986. }
  32987. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32988. };
  32989. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32990. __decorate([
  32991. BABYLON.serializeAsImageProcessingConfiguration()
  32992. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32993. __decorate([
  32994. BABYLON.serialize()
  32995. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32996. return PBRBaseMaterial;
  32997. }(BABYLON.PushMaterial));
  32998. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32999. })(BABYLON || (BABYLON = {}));
  33000. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  33001. var BABYLON;
  33002. (function (BABYLON) {
  33003. var Internals;
  33004. (function (Internals) {
  33005. /**
  33006. * The Physically based simple base material of BJS.
  33007. *
  33008. * This enables better naming and convention enforcements on top of the pbrMaterial.
  33009. * It is used as the base class for both the specGloss and metalRough conventions.
  33010. */
  33011. var PBRBaseSimpleMaterial = (function (_super) {
  33012. __extends(PBRBaseSimpleMaterial, _super);
  33013. /**
  33014. * Instantiates a new PBRMaterial instance.
  33015. *
  33016. * @param name The material name
  33017. * @param scene The scene the material will be use in.
  33018. */
  33019. function PBRBaseSimpleMaterial(name, scene) {
  33020. var _this = _super.call(this, name, scene) || this;
  33021. /**
  33022. * Number of Simultaneous lights allowed on the material.
  33023. */
  33024. _this.maxSimultaneousLights = 4;
  33025. /**
  33026. * If sets to true, disables all the lights affecting the material.
  33027. */
  33028. _this.disableLighting = false;
  33029. /**
  33030. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33031. */
  33032. _this.invertNormalMapX = false;
  33033. /**
  33034. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33035. */
  33036. _this.invertNormalMapY = false;
  33037. /**
  33038. * Emissivie color used to self-illuminate the model.
  33039. */
  33040. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33041. /**
  33042. * Occlusion Channel Strenght.
  33043. */
  33044. _this.occlusionStrength = 1.0;
  33045. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33046. _this._useAmbientInGrayScale = true;
  33047. return _this;
  33048. }
  33049. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  33050. /**
  33051. * Gets the current transparency mode.
  33052. */
  33053. get: function () {
  33054. return this._transparencyMode;
  33055. },
  33056. /**
  33057. * Sets the transparency mode of the material.
  33058. */
  33059. set: function (value) {
  33060. if (this._transparencyMode === value) {
  33061. return;
  33062. }
  33063. this._transparencyMode = value;
  33064. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  33065. this._forceAlphaTest = true;
  33066. }
  33067. else {
  33068. this._forceAlphaTest = false;
  33069. }
  33070. this._markAllSubMeshesAsTexturesDirty();
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  33076. /**
  33077. * Gets the current double sided mode.
  33078. */
  33079. get: function () {
  33080. return this._twoSidedLighting;
  33081. },
  33082. /**
  33083. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33084. */
  33085. set: function (value) {
  33086. if (this._twoSidedLighting === value) {
  33087. return;
  33088. }
  33089. this._twoSidedLighting = value;
  33090. this.backFaceCulling = !value;
  33091. this._markAllSubMeshesAsTexturesDirty();
  33092. },
  33093. enumerable: true,
  33094. configurable: true
  33095. });
  33096. /**
  33097. * Specifies wether or not the alpha value of the albedo texture should be used.
  33098. */
  33099. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33100. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33101. };
  33102. /**
  33103. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  33104. */
  33105. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  33106. if (this._linkRefractionWithTransparency) {
  33107. return false;
  33108. }
  33109. return (this.alpha < 1.0) ||
  33110. (this._shouldUseAlphaFromAlbedoTexture() &&
  33111. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  33112. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  33113. };
  33114. /**
  33115. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  33116. */
  33117. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33118. if (this._linkRefractionWithTransparency) {
  33119. return false;
  33120. }
  33121. return this._shouldUseAlphaFromAlbedoTexture() &&
  33122. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33123. };
  33124. /**
  33125. * Return the active textures of the material.
  33126. */
  33127. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33128. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33129. if (this.environmentTexture) {
  33130. activeTextures.push(this.environmentTexture);
  33131. }
  33132. if (this.normalTexture) {
  33133. activeTextures.push(this.normalTexture);
  33134. }
  33135. if (this.emissiveTexture) {
  33136. activeTextures.push(this.emissiveTexture);
  33137. }
  33138. if (this.occlusionTexture) {
  33139. activeTextures.push(this.occlusionTexture);
  33140. }
  33141. return activeTextures;
  33142. };
  33143. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33144. return "PBRBaseSimpleMaterial";
  33145. };
  33146. __decorate([
  33147. BABYLON.serialize(),
  33148. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33149. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33150. __decorate([
  33151. BABYLON.serialize(),
  33152. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33153. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33154. __decorate([
  33155. BABYLON.serializeAsTexture(),
  33156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33157. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33158. __decorate([
  33159. BABYLON.serialize(),
  33160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33161. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33162. __decorate([
  33163. BABYLON.serialize(),
  33164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33165. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33166. __decorate([
  33167. BABYLON.serializeAsTexture(),
  33168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33169. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33170. __decorate([
  33171. BABYLON.serializeAsColor3("emissive"),
  33172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33173. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33174. __decorate([
  33175. BABYLON.serializeAsTexture(),
  33176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33177. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33178. __decorate([
  33179. BABYLON.serialize(),
  33180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33181. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33182. __decorate([
  33183. BABYLON.serializeAsTexture(),
  33184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33185. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33186. __decorate([
  33187. BABYLON.serialize(),
  33188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33189. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33190. __decorate([
  33191. BABYLON.serialize()
  33192. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33193. __decorate([
  33194. BABYLON.serialize()
  33195. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33196. return PBRBaseSimpleMaterial;
  33197. }(BABYLON.PBRBaseMaterial));
  33198. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33199. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33200. })(BABYLON || (BABYLON = {}));
  33201. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33202. var BABYLON;
  33203. (function (BABYLON) {
  33204. /**
  33205. * The Physically based material of BJS.
  33206. *
  33207. * This offers the main features of a standard PBR material.
  33208. * For more information, please refer to the documentation :
  33209. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33210. */
  33211. var PBRMaterial = (function (_super) {
  33212. __extends(PBRMaterial, _super);
  33213. /**
  33214. * Instantiates a new PBRMaterial instance.
  33215. *
  33216. * @param name The material name
  33217. * @param scene The scene the material will be use in.
  33218. */
  33219. function PBRMaterial(name, scene) {
  33220. var _this = _super.call(this, name, scene) || this;
  33221. /**
  33222. * Intensity of the direct lights e.g. the four lights available in your scene.
  33223. * This impacts both the direct diffuse and specular highlights.
  33224. */
  33225. _this.directIntensity = 1.0;
  33226. /**
  33227. * Intensity of the emissive part of the material.
  33228. * This helps controlling the emissive effect without modifying the emissive color.
  33229. */
  33230. _this.emissiveIntensity = 1.0;
  33231. /**
  33232. * Intensity of the environment e.g. how much the environment will light the object
  33233. * either through harmonics for rough material or through the refelction for shiny ones.
  33234. */
  33235. _this.environmentIntensity = 1.0;
  33236. /**
  33237. * This is a special control allowing the reduction of the specular highlights coming from the
  33238. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33239. */
  33240. _this.specularIntensity = 1.0;
  33241. /**
  33242. * Debug Control allowing disabling the bump map on this material.
  33243. */
  33244. _this.disableBumpMap = false;
  33245. /**
  33246. * AKA Occlusion Texture Intensity in other nomenclature.
  33247. */
  33248. _this.ambientTextureStrength = 1.0;
  33249. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33250. /**
  33251. * AKA Diffuse Color in other nomenclature.
  33252. */
  33253. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33254. /**
  33255. * AKA Specular Color in other nomenclature.
  33256. */
  33257. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33258. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33259. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33260. /**
  33261. * AKA Glossiness in other nomenclature.
  33262. */
  33263. _this.microSurface = 1.0;
  33264. /**
  33265. * source material index of refraction (IOR)' / 'destination material IOR.
  33266. */
  33267. _this.indexOfRefraction = 0.66;
  33268. /**
  33269. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33270. */
  33271. _this.invertRefractionY = false;
  33272. /**
  33273. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33274. * Materials half opaque for instance using refraction could benefit from this control.
  33275. */
  33276. _this.linkRefractionWithTransparency = false;
  33277. _this.useLightmapAsShadowmap = false;
  33278. /**
  33279. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33280. */
  33281. _this.useAlphaFromAlbedoTexture = false;
  33282. /**
  33283. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33284. */
  33285. _this.forceAlphaTest = false;
  33286. /**
  33287. * Defines the alpha limits in alpha test mode.
  33288. */
  33289. _this.alphaCutOff = 0.4;
  33290. /**
  33291. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33292. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33293. */
  33294. _this.useSpecularOverAlpha = true;
  33295. /**
  33296. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33297. */
  33298. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33299. /**
  33300. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33301. */
  33302. _this.useRoughnessFromMetallicTextureAlpha = true;
  33303. /**
  33304. * Specifies if the metallic texture contains the roughness information in its green channel.
  33305. */
  33306. _this.useRoughnessFromMetallicTextureGreen = false;
  33307. /**
  33308. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33309. */
  33310. _this.useMetallnessFromMetallicTextureBlue = false;
  33311. /**
  33312. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33313. */
  33314. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33315. /**
  33316. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33317. */
  33318. _this.useAmbientInGrayScale = false;
  33319. /**
  33320. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33321. * The material will try to infer what glossiness each pixel should be.
  33322. */
  33323. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33324. /**
  33325. * BJS is using an harcoded light falloff based on a manually sets up range.
  33326. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33327. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33328. */
  33329. _this.usePhysicalLightFalloff = true;
  33330. /**
  33331. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33332. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33333. */
  33334. _this.useRadianceOverAlpha = true;
  33335. /**
  33336. * Allows using the bump map in parallax mode.
  33337. */
  33338. _this.useParallax = false;
  33339. /**
  33340. * Allows using the bump map in parallax occlusion mode.
  33341. */
  33342. _this.useParallaxOcclusion = false;
  33343. /**
  33344. * Controls the scale bias of the parallax mode.
  33345. */
  33346. _this.parallaxScaleBias = 0.05;
  33347. /**
  33348. * If sets to true, disables all the lights affecting the material.
  33349. */
  33350. _this.disableLighting = false;
  33351. /**
  33352. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33353. */
  33354. _this.forceIrradianceInFragment = false;
  33355. /**
  33356. * Number of Simultaneous lights allowed on the material.
  33357. */
  33358. _this.maxSimultaneousLights = 4;
  33359. /**
  33360. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33361. */
  33362. _this.invertNormalMapX = false;
  33363. /**
  33364. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33365. */
  33366. _this.invertNormalMapY = false;
  33367. /**
  33368. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33369. */
  33370. _this.twoSidedLighting = false;
  33371. /**
  33372. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33373. * in your scene composition.
  33374. */
  33375. _this.preMultiplyAlpha = false;
  33376. /**
  33377. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33378. * And/Or occlude the blended part.
  33379. */
  33380. _this.useAlphaFresnel = false;
  33381. /**
  33382. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33383. * And/Or occlude the blended part.
  33384. */
  33385. _this.environmentBRDFTexture = null;
  33386. /**
  33387. * Force normal to face away from face.
  33388. * (Temporary internal fix to remove before 3.1)
  33389. */
  33390. _this.forceNormalForward = false;
  33391. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33392. return _this;
  33393. }
  33394. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33395. /**
  33396. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33397. */
  33398. get: function () {
  33399. return this._PBRMATERIAL_OPAQUE;
  33400. },
  33401. enumerable: true,
  33402. configurable: true
  33403. });
  33404. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33405. /**
  33406. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33407. */
  33408. get: function () {
  33409. return this._PBRMATERIAL_ALPHATEST;
  33410. },
  33411. enumerable: true,
  33412. configurable: true
  33413. });
  33414. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33415. /**
  33416. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33417. */
  33418. get: function () {
  33419. return this._PBRMATERIAL_ALPHABLEND;
  33420. },
  33421. enumerable: true,
  33422. configurable: true
  33423. });
  33424. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33425. /**
  33426. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33427. * They are also discarded below the alpha cutoff threshold to improve performances.
  33428. */
  33429. get: function () {
  33430. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33431. },
  33432. enumerable: true,
  33433. configurable: true
  33434. });
  33435. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33436. /**
  33437. * Gets the image processing configuration used either in this material.
  33438. */
  33439. get: function () {
  33440. return this._imageProcessingConfiguration;
  33441. },
  33442. /**
  33443. * Sets the Default image processing configuration used either in the this material.
  33444. *
  33445. * If sets to null, the scene one is in use.
  33446. */
  33447. set: function (value) {
  33448. this._attachImageProcessingConfiguration(value);
  33449. // Ensure the effect will be rebuilt.
  33450. this._markAllSubMeshesAsTexturesDirty();
  33451. },
  33452. enumerable: true,
  33453. configurable: true
  33454. });
  33455. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33456. /**
  33457. * Gets wether the color curves effect is enabled.
  33458. */
  33459. get: function () {
  33460. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33461. },
  33462. /**
  33463. * Sets wether the color curves effect is enabled.
  33464. */
  33465. set: function (value) {
  33466. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33467. },
  33468. enumerable: true,
  33469. configurable: true
  33470. });
  33471. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33472. /**
  33473. * Gets wether the color grading effect is enabled.
  33474. */
  33475. get: function () {
  33476. return this.imageProcessingConfiguration.colorGradingEnabled;
  33477. },
  33478. /**
  33479. * Gets wether the color grading effect is enabled.
  33480. */
  33481. set: function (value) {
  33482. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33483. },
  33484. enumerable: true,
  33485. configurable: true
  33486. });
  33487. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33488. /**
  33489. * Gets wether tonemapping is enabled or not.
  33490. */
  33491. get: function () {
  33492. return this._imageProcessingConfiguration.toneMappingEnabled;
  33493. },
  33494. /**
  33495. * Sets wether tonemapping is enabled or not
  33496. */
  33497. set: function (value) {
  33498. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33499. },
  33500. enumerable: true,
  33501. configurable: true
  33502. });
  33503. ;
  33504. ;
  33505. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33506. /**
  33507. * The camera exposure used on this material.
  33508. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33509. * This corresponds to a photographic exposure.
  33510. */
  33511. get: function () {
  33512. return this._imageProcessingConfiguration.exposure;
  33513. },
  33514. /**
  33515. * The camera exposure used on this material.
  33516. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33517. * This corresponds to a photographic exposure.
  33518. */
  33519. set: function (value) {
  33520. this._imageProcessingConfiguration.exposure = value;
  33521. },
  33522. enumerable: true,
  33523. configurable: true
  33524. });
  33525. ;
  33526. ;
  33527. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33528. /**
  33529. * Gets The camera contrast used on this material.
  33530. */
  33531. get: function () {
  33532. return this._imageProcessingConfiguration.contrast;
  33533. },
  33534. /**
  33535. * Sets The camera contrast used on this material.
  33536. */
  33537. set: function (value) {
  33538. this._imageProcessingConfiguration.contrast = value;
  33539. },
  33540. enumerable: true,
  33541. configurable: true
  33542. });
  33543. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33544. /**
  33545. * Gets the Color Grading 2D Lookup Texture.
  33546. */
  33547. get: function () {
  33548. return this._imageProcessingConfiguration.colorGradingTexture;
  33549. },
  33550. /**
  33551. * Sets the Color Grading 2D Lookup Texture.
  33552. */
  33553. set: function (value) {
  33554. this._imageProcessingConfiguration.colorGradingTexture = value;
  33555. },
  33556. enumerable: true,
  33557. configurable: true
  33558. });
  33559. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33560. /**
  33561. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33562. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33563. * 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;
  33564. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33565. */
  33566. get: function () {
  33567. return this._imageProcessingConfiguration.colorCurves;
  33568. },
  33569. /**
  33570. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33571. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33572. * 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;
  33573. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33574. */
  33575. set: function (value) {
  33576. this._imageProcessingConfiguration.colorCurves = value;
  33577. },
  33578. enumerable: true,
  33579. configurable: true
  33580. });
  33581. PBRMaterial.prototype.getClassName = function () {
  33582. return "PBRMaterial";
  33583. };
  33584. PBRMaterial.prototype.getActiveTextures = function () {
  33585. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33586. if (this._albedoTexture) {
  33587. activeTextures.push(this._albedoTexture);
  33588. }
  33589. if (this._ambientTexture) {
  33590. activeTextures.push(this._ambientTexture);
  33591. }
  33592. if (this._opacityTexture) {
  33593. activeTextures.push(this._opacityTexture);
  33594. }
  33595. if (this._reflectionTexture) {
  33596. activeTextures.push(this._reflectionTexture);
  33597. }
  33598. if (this._emissiveTexture) {
  33599. activeTextures.push(this._emissiveTexture);
  33600. }
  33601. if (this._reflectivityTexture) {
  33602. activeTextures.push(this._reflectivityTexture);
  33603. }
  33604. if (this._metallicTexture) {
  33605. activeTextures.push(this._metallicTexture);
  33606. }
  33607. if (this._microSurfaceTexture) {
  33608. activeTextures.push(this._microSurfaceTexture);
  33609. }
  33610. if (this._bumpTexture) {
  33611. activeTextures.push(this._bumpTexture);
  33612. }
  33613. if (this._lightmapTexture) {
  33614. activeTextures.push(this._lightmapTexture);
  33615. }
  33616. if (this._refractionTexture) {
  33617. activeTextures.push(this._refractionTexture);
  33618. }
  33619. return activeTextures;
  33620. };
  33621. PBRMaterial.prototype.hasTexture = function (texture) {
  33622. if (_super.prototype.hasTexture.call(this, texture)) {
  33623. return true;
  33624. }
  33625. if (this._albedoTexture === texture) {
  33626. return true;
  33627. }
  33628. if (this._ambientTexture === texture) {
  33629. return true;
  33630. }
  33631. if (this._opacityTexture === texture) {
  33632. return true;
  33633. }
  33634. if (this._reflectionTexture === texture) {
  33635. return true;
  33636. }
  33637. if (this._reflectivityTexture === texture) {
  33638. return true;
  33639. }
  33640. if (this._metallicTexture === texture) {
  33641. return true;
  33642. }
  33643. if (this._microSurfaceTexture === texture) {
  33644. return true;
  33645. }
  33646. if (this._bumpTexture === texture) {
  33647. return true;
  33648. }
  33649. if (this._lightmapTexture === texture) {
  33650. return true;
  33651. }
  33652. if (this._refractionTexture === texture) {
  33653. return true;
  33654. }
  33655. return false;
  33656. };
  33657. PBRMaterial.prototype.clone = function (name) {
  33658. var _this = this;
  33659. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33660. };
  33661. PBRMaterial.prototype.serialize = function () {
  33662. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33663. serializationObject.customType = "BABYLON.PBRMaterial";
  33664. return serializationObject;
  33665. };
  33666. // Statics
  33667. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33668. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33669. };
  33670. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33671. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33672. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33673. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33674. __decorate([
  33675. BABYLON.serialize(),
  33676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33677. ], PBRMaterial.prototype, "directIntensity", void 0);
  33678. __decorate([
  33679. BABYLON.serialize(),
  33680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33681. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33682. __decorate([
  33683. BABYLON.serialize(),
  33684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33685. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33686. __decorate([
  33687. BABYLON.serialize(),
  33688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33689. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33690. __decorate([
  33691. BABYLON.serialize(),
  33692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33693. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33694. __decorate([
  33695. BABYLON.serializeAsTexture(),
  33696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33697. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33698. __decorate([
  33699. BABYLON.serializeAsTexture(),
  33700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33701. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33702. __decorate([
  33703. BABYLON.serialize(),
  33704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33705. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33706. __decorate([
  33707. BABYLON.serializeAsTexture(),
  33708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33709. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33710. __decorate([
  33711. BABYLON.serializeAsTexture(),
  33712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33713. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33714. __decorate([
  33715. BABYLON.serializeAsTexture(),
  33716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33717. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33718. __decorate([
  33719. BABYLON.serializeAsTexture(),
  33720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33721. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33722. __decorate([
  33723. BABYLON.serializeAsTexture(),
  33724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33725. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33726. __decorate([
  33727. BABYLON.serialize(),
  33728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33729. ], PBRMaterial.prototype, "metallic", void 0);
  33730. __decorate([
  33731. BABYLON.serialize(),
  33732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33733. ], PBRMaterial.prototype, "roughness", void 0);
  33734. __decorate([
  33735. BABYLON.serializeAsTexture(),
  33736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33737. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33738. __decorate([
  33739. BABYLON.serializeAsTexture(),
  33740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33741. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33742. __decorate([
  33743. BABYLON.serializeAsTexture(),
  33744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33745. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33746. __decorate([
  33747. BABYLON.serializeAsTexture(),
  33748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33749. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33750. __decorate([
  33751. BABYLON.serializeAsColor3("ambient"),
  33752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33753. ], PBRMaterial.prototype, "ambientColor", void 0);
  33754. __decorate([
  33755. BABYLON.serializeAsColor3("albedo"),
  33756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33757. ], PBRMaterial.prototype, "albedoColor", void 0);
  33758. __decorate([
  33759. BABYLON.serializeAsColor3("reflectivity"),
  33760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33761. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33762. __decorate([
  33763. BABYLON.serializeAsColor3("reflection"),
  33764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33765. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33766. __decorate([
  33767. BABYLON.serializeAsColor3("emissive"),
  33768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33769. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33770. __decorate([
  33771. BABYLON.serialize(),
  33772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33773. ], PBRMaterial.prototype, "microSurface", void 0);
  33774. __decorate([
  33775. BABYLON.serialize(),
  33776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33777. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33778. __decorate([
  33779. BABYLON.serialize(),
  33780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33781. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33782. __decorate([
  33783. BABYLON.serialize(),
  33784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33785. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33786. __decorate([
  33787. BABYLON.serialize(),
  33788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33789. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33790. __decorate([
  33791. BABYLON.serialize(),
  33792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33793. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33794. __decorate([
  33795. BABYLON.serialize(),
  33796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33797. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33798. __decorate([
  33799. BABYLON.serialize(),
  33800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33801. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33802. __decorate([
  33803. BABYLON.serialize(),
  33804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33805. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33806. __decorate([
  33807. BABYLON.serialize(),
  33808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33809. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33810. __decorate([
  33811. BABYLON.serialize(),
  33812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33813. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33814. __decorate([
  33815. BABYLON.serialize(),
  33816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33817. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33818. __decorate([
  33819. BABYLON.serialize(),
  33820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33821. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33822. __decorate([
  33823. BABYLON.serialize(),
  33824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33825. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33826. __decorate([
  33827. BABYLON.serialize(),
  33828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33829. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33830. __decorate([
  33831. BABYLON.serialize(),
  33832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33833. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33834. __decorate([
  33835. BABYLON.serialize(),
  33836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33837. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33838. __decorate([
  33839. BABYLON.serialize(),
  33840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33841. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33842. __decorate([
  33843. BABYLON.serialize(),
  33844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33845. ], PBRMaterial.prototype, "useParallax", void 0);
  33846. __decorate([
  33847. BABYLON.serialize(),
  33848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33849. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33850. __decorate([
  33851. BABYLON.serialize(),
  33852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33853. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33854. __decorate([
  33855. BABYLON.serialize(),
  33856. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33857. ], PBRMaterial.prototype, "disableLighting", void 0);
  33858. __decorate([
  33859. BABYLON.serialize(),
  33860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33861. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33862. __decorate([
  33863. BABYLON.serialize(),
  33864. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33865. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33866. __decorate([
  33867. BABYLON.serialize(),
  33868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33869. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33870. __decorate([
  33871. BABYLON.serialize(),
  33872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33873. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33874. __decorate([
  33875. BABYLON.serialize(),
  33876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33877. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33878. __decorate([
  33879. BABYLON.serialize(),
  33880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33881. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33882. __decorate([
  33883. BABYLON.serialize(),
  33884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33885. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33886. __decorate([
  33887. BABYLON.serializeAsTexture(),
  33888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33889. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33890. __decorate([
  33891. BABYLON.serialize(),
  33892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33893. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33894. return PBRMaterial;
  33895. }(BABYLON.PBRBaseMaterial));
  33896. BABYLON.PBRMaterial = PBRMaterial;
  33897. })(BABYLON || (BABYLON = {}));
  33898. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33899. var BABYLON;
  33900. (function (BABYLON) {
  33901. /**
  33902. * The PBR material of BJS following the metal roughness convention.
  33903. *
  33904. * This fits to the PBR convention in the GLTF definition:
  33905. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33906. */
  33907. var PBRMetallicRoughnessMaterial = (function (_super) {
  33908. __extends(PBRMetallicRoughnessMaterial, _super);
  33909. /**
  33910. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33911. *
  33912. * @param name The material name
  33913. * @param scene The scene the material will be use in.
  33914. */
  33915. function PBRMetallicRoughnessMaterial(name, scene) {
  33916. var _this = _super.call(this, name, scene) || this;
  33917. _this._useRoughnessFromMetallicTextureAlpha = false;
  33918. _this._useRoughnessFromMetallicTextureGreen = true;
  33919. _this._useMetallnessFromMetallicTextureBlue = true;
  33920. return _this;
  33921. }
  33922. /**
  33923. * Return the currrent class name of the material.
  33924. */
  33925. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33926. return "PBRMetallicRoughnessMaterial";
  33927. };
  33928. /**
  33929. * Return the active textures of the material.
  33930. */
  33931. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33932. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33933. if (this.baseTexture) {
  33934. activeTextures.push(this.baseTexture);
  33935. }
  33936. if (this.metallicRoughnessTexture) {
  33937. activeTextures.push(this.metallicRoughnessTexture);
  33938. }
  33939. return activeTextures;
  33940. };
  33941. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33942. if (_super.prototype.hasTexture.call(this, texture)) {
  33943. return true;
  33944. }
  33945. if (this.baseTexture === texture) {
  33946. return true;
  33947. }
  33948. if (this.metallicRoughnessTexture === texture) {
  33949. return true;
  33950. }
  33951. return false;
  33952. };
  33953. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33954. var _this = this;
  33955. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33956. };
  33957. /**
  33958. * Serialize the material to a parsable JSON object.
  33959. */
  33960. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33961. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33962. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33963. return serializationObject;
  33964. };
  33965. /**
  33966. * Parses a JSON object correponding to the serialize function.
  33967. */
  33968. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33969. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33970. };
  33971. __decorate([
  33972. BABYLON.serializeAsColor3(),
  33973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33974. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33975. __decorate([
  33976. BABYLON.serializeAsTexture(),
  33977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33978. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33979. __decorate([
  33980. BABYLON.serialize(),
  33981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33982. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33983. __decorate([
  33984. BABYLON.serialize(),
  33985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33986. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33987. __decorate([
  33988. BABYLON.serializeAsTexture(),
  33989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33990. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33991. return PBRMetallicRoughnessMaterial;
  33992. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33993. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33994. })(BABYLON || (BABYLON = {}));
  33995. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33996. var BABYLON;
  33997. (function (BABYLON) {
  33998. /**
  33999. * The PBR material of BJS following the specular glossiness convention.
  34000. *
  34001. * This fits to the PBR convention in the GLTF definition:
  34002. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34003. */
  34004. var PBRSpecularGlossinessMaterial = (function (_super) {
  34005. __extends(PBRSpecularGlossinessMaterial, _super);
  34006. /**
  34007. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  34008. *
  34009. * @param name The material name
  34010. * @param scene The scene the material will be use in.
  34011. */
  34012. function PBRSpecularGlossinessMaterial(name, scene) {
  34013. var _this = _super.call(this, name, scene) || this;
  34014. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  34015. return _this;
  34016. }
  34017. /**
  34018. * Return the currrent class name of the material.
  34019. */
  34020. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  34021. return "PBRSpecularGlossinessMaterial";
  34022. };
  34023. /**
  34024. * Return the active textures of the material.
  34025. */
  34026. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  34027. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34028. if (this.diffuseTexture) {
  34029. activeTextures.push(this.diffuseTexture);
  34030. }
  34031. if (this.specularGlossinessTexture) {
  34032. activeTextures.push(this.specularGlossinessTexture);
  34033. }
  34034. return activeTextures;
  34035. };
  34036. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  34037. if (_super.prototype.hasTexture.call(this, texture)) {
  34038. return true;
  34039. }
  34040. if (this.diffuseTexture === texture) {
  34041. return true;
  34042. }
  34043. if (this.specularGlossinessTexture === texture) {
  34044. return true;
  34045. }
  34046. return false;
  34047. };
  34048. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  34049. var _this = this;
  34050. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  34051. };
  34052. /**
  34053. * Serialize the material to a parsable JSON object.
  34054. */
  34055. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  34056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34057. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  34058. return serializationObject;
  34059. };
  34060. /**
  34061. * Parses a JSON object correponding to the serialize function.
  34062. */
  34063. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  34064. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  34065. };
  34066. __decorate([
  34067. BABYLON.serializeAsColor3("diffuse"),
  34068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34069. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  34070. __decorate([
  34071. BABYLON.serializeAsTexture(),
  34072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34073. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  34074. __decorate([
  34075. BABYLON.serializeAsColor3("specular"),
  34076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  34077. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  34078. __decorate([
  34079. BABYLON.serialize(),
  34080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  34081. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  34082. __decorate([
  34083. BABYLON.serializeAsTexture(),
  34084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  34085. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  34086. return PBRSpecularGlossinessMaterial;
  34087. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34088. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  34089. })(BABYLON || (BABYLON = {}));
  34090. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  34091. var BABYLON;
  34092. (function (BABYLON) {
  34093. BABYLON.CameraInputTypes = {};
  34094. var CameraInputsManager = (function () {
  34095. function CameraInputsManager(camera) {
  34096. this.attached = {};
  34097. this.camera = camera;
  34098. this.checkInputs = function () { };
  34099. }
  34100. CameraInputsManager.prototype.add = function (input) {
  34101. var type = input.getSimpleName();
  34102. if (this.attached[type]) {
  34103. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  34104. return;
  34105. }
  34106. this.attached[type] = input;
  34107. input.camera = this.camera;
  34108. //for checkInputs, we are dynamically creating a function
  34109. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  34110. if (input.checkInputs) {
  34111. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34112. }
  34113. if (this.attachedElement) {
  34114. input.attachControl(this.attachedElement);
  34115. }
  34116. };
  34117. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34118. for (var cam in this.attached) {
  34119. var input = this.attached[cam];
  34120. if (input === inputToRemove) {
  34121. input.detachControl(this.attachedElement);
  34122. input.camera = null;
  34123. delete this.attached[cam];
  34124. this.rebuildInputCheck();
  34125. }
  34126. }
  34127. };
  34128. CameraInputsManager.prototype.removeByType = function (inputType) {
  34129. for (var cam in this.attached) {
  34130. var input = this.attached[cam];
  34131. if (input.getClassName() === inputType) {
  34132. input.detachControl(this.attachedElement);
  34133. input.camera = null;
  34134. delete this.attached[cam];
  34135. this.rebuildInputCheck();
  34136. }
  34137. }
  34138. };
  34139. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34140. var current = this.checkInputs;
  34141. return function () {
  34142. current();
  34143. fn();
  34144. };
  34145. };
  34146. CameraInputsManager.prototype.attachInput = function (input) {
  34147. input.attachControl(this.attachedElement, this.noPreventDefault);
  34148. };
  34149. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34150. if (this.attachedElement) {
  34151. return;
  34152. }
  34153. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34154. this.attachedElement = element;
  34155. this.noPreventDefault = noPreventDefault;
  34156. for (var cam in this.attached) {
  34157. var input = this.attached[cam];
  34158. this.attached[cam].attachControl(element, noPreventDefault);
  34159. }
  34160. };
  34161. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34162. if (disconnect === void 0) { disconnect = false; }
  34163. if (this.attachedElement !== element) {
  34164. return;
  34165. }
  34166. for (var cam in this.attached) {
  34167. var input = this.attached[cam];
  34168. this.attached[cam].detachControl(element);
  34169. if (disconnect) {
  34170. this.attached[cam].camera = null;
  34171. }
  34172. }
  34173. this.attachedElement = null;
  34174. };
  34175. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34176. this.checkInputs = function () { };
  34177. for (var cam in this.attached) {
  34178. var input = this.attached[cam];
  34179. if (input.checkInputs) {
  34180. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34181. }
  34182. }
  34183. };
  34184. CameraInputsManager.prototype.clear = function () {
  34185. if (this.attachedElement) {
  34186. this.detachElement(this.attachedElement, true);
  34187. }
  34188. this.attached = {};
  34189. this.attachedElement = null;
  34190. this.checkInputs = function () { };
  34191. };
  34192. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34193. var inputs = {};
  34194. for (var cam in this.attached) {
  34195. var input = this.attached[cam];
  34196. var res = BABYLON.SerializationHelper.Serialize(input);
  34197. inputs[input.getClassName()] = res;
  34198. }
  34199. serializedCamera.inputsmgr = inputs;
  34200. };
  34201. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34202. var parsedInputs = parsedCamera.inputsmgr;
  34203. if (parsedInputs) {
  34204. this.clear();
  34205. for (var n in parsedInputs) {
  34206. var construct = BABYLON.CameraInputTypes[n];
  34207. if (construct) {
  34208. var parsedinput = parsedInputs[n];
  34209. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34210. this.add(input);
  34211. }
  34212. }
  34213. }
  34214. else {
  34215. //2016-03-08 this part is for managing backward compatibility
  34216. for (var n in this.attached) {
  34217. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34218. if (construct) {
  34219. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34220. this.remove(this.attached[n]);
  34221. this.add(input);
  34222. }
  34223. }
  34224. }
  34225. };
  34226. return CameraInputsManager;
  34227. }());
  34228. BABYLON.CameraInputsManager = CameraInputsManager;
  34229. })(BABYLON || (BABYLON = {}));
  34230. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34231. var BABYLON;
  34232. (function (BABYLON) {
  34233. var FreeCameraMouseInput = (function () {
  34234. function FreeCameraMouseInput(touchEnabled) {
  34235. if (touchEnabled === void 0) { touchEnabled = true; }
  34236. this.touchEnabled = touchEnabled;
  34237. this.buttons = [0, 1, 2];
  34238. this.angularSensibility = 2000.0;
  34239. }
  34240. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34241. var _this = this;
  34242. var engine = this.camera.getEngine();
  34243. if (!this._pointerInput) {
  34244. this._pointerInput = function (p, s) {
  34245. var evt = p.event;
  34246. if (engine.isInVRExclusivePointerMode) {
  34247. return;
  34248. }
  34249. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34250. return;
  34251. }
  34252. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34253. return;
  34254. }
  34255. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34256. try {
  34257. evt.srcElement.setPointerCapture(evt.pointerId);
  34258. }
  34259. catch (e) {
  34260. //Nothing to do with the error. Execution will continue.
  34261. }
  34262. _this.previousPosition = {
  34263. x: evt.clientX,
  34264. y: evt.clientY
  34265. };
  34266. if (!noPreventDefault) {
  34267. evt.preventDefault();
  34268. element.focus();
  34269. }
  34270. }
  34271. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34272. try {
  34273. evt.srcElement.releasePointerCapture(evt.pointerId);
  34274. }
  34275. catch (e) {
  34276. //Nothing to do with the error.
  34277. }
  34278. _this.previousPosition = null;
  34279. if (!noPreventDefault) {
  34280. evt.preventDefault();
  34281. }
  34282. }
  34283. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34284. if (!_this.previousPosition || engine.isPointerLock) {
  34285. return;
  34286. }
  34287. var offsetX = evt.clientX - _this.previousPosition.x;
  34288. var offsetY = evt.clientY - _this.previousPosition.y;
  34289. if (_this.camera.getScene().useRightHandedSystem) {
  34290. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34291. }
  34292. else {
  34293. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34294. }
  34295. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34296. _this.previousPosition = {
  34297. x: evt.clientX,
  34298. y: evt.clientY
  34299. };
  34300. if (!noPreventDefault) {
  34301. evt.preventDefault();
  34302. }
  34303. }
  34304. };
  34305. }
  34306. this._onMouseMove = function (evt) {
  34307. if (!engine.isPointerLock) {
  34308. return;
  34309. }
  34310. if (engine.isInVRExclusivePointerMode) {
  34311. return;
  34312. }
  34313. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34314. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34315. if (_this.camera.getScene().useRightHandedSystem) {
  34316. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34317. }
  34318. else {
  34319. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34320. }
  34321. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34322. _this.previousPosition = null;
  34323. if (!noPreventDefault) {
  34324. evt.preventDefault();
  34325. }
  34326. };
  34327. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34328. element.addEventListener("mousemove", this._onMouseMove, false);
  34329. };
  34330. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34331. if (this._observer && element) {
  34332. this.camera.getScene().onPointerObservable.remove(this._observer);
  34333. element.removeEventListener("mousemove", this._onMouseMove);
  34334. this._observer = null;
  34335. this._onMouseMove = null;
  34336. this.previousPosition = null;
  34337. }
  34338. };
  34339. FreeCameraMouseInput.prototype.getClassName = function () {
  34340. return "FreeCameraMouseInput";
  34341. };
  34342. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34343. return "mouse";
  34344. };
  34345. __decorate([
  34346. BABYLON.serialize()
  34347. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34348. __decorate([
  34349. BABYLON.serialize()
  34350. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34351. return FreeCameraMouseInput;
  34352. }());
  34353. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34354. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34355. })(BABYLON || (BABYLON = {}));
  34356. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34357. var BABYLON;
  34358. (function (BABYLON) {
  34359. var FreeCameraKeyboardMoveInput = (function () {
  34360. function FreeCameraKeyboardMoveInput() {
  34361. this._keys = [];
  34362. this.keysUp = [38];
  34363. this.keysDown = [40];
  34364. this.keysLeft = [37];
  34365. this.keysRight = [39];
  34366. }
  34367. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34368. var _this = this;
  34369. if (this._onCanvasBlurObserver) {
  34370. return;
  34371. }
  34372. this._scene = this.camera.getScene();
  34373. this._engine = this._scene.getEngine();
  34374. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34375. _this._keys = [];
  34376. });
  34377. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34378. var evt = info.event;
  34379. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34380. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34381. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34382. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34383. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34384. var index = _this._keys.indexOf(evt.keyCode);
  34385. if (index === -1) {
  34386. _this._keys.push(evt.keyCode);
  34387. }
  34388. if (!noPreventDefault) {
  34389. evt.preventDefault();
  34390. }
  34391. }
  34392. }
  34393. else {
  34394. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34395. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34396. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34397. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34398. var index = _this._keys.indexOf(evt.keyCode);
  34399. if (index >= 0) {
  34400. _this._keys.splice(index, 1);
  34401. }
  34402. if (!noPreventDefault) {
  34403. evt.preventDefault();
  34404. }
  34405. }
  34406. }
  34407. });
  34408. };
  34409. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34410. if (this._scene) {
  34411. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34412. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34413. this._onKeyboardObserver = null;
  34414. this._onCanvasBlurObserver = null;
  34415. }
  34416. this._keys = [];
  34417. };
  34418. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34419. if (this._onKeyboardObserver) {
  34420. var camera = this.camera;
  34421. // Keyboard
  34422. for (var index = 0; index < this._keys.length; index++) {
  34423. var keyCode = this._keys[index];
  34424. var speed = camera._computeLocalCameraSpeed();
  34425. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34426. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34427. }
  34428. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34429. camera._localDirection.copyFromFloats(0, 0, speed);
  34430. }
  34431. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34432. camera._localDirection.copyFromFloats(speed, 0, 0);
  34433. }
  34434. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34435. camera._localDirection.copyFromFloats(0, 0, -speed);
  34436. }
  34437. if (camera.getScene().useRightHandedSystem) {
  34438. camera._localDirection.z *= -1;
  34439. }
  34440. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34441. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34442. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34443. }
  34444. }
  34445. };
  34446. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34447. return "FreeCameraKeyboardMoveInput";
  34448. };
  34449. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34450. this._keys = [];
  34451. };
  34452. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34453. return "keyboard";
  34454. };
  34455. __decorate([
  34456. BABYLON.serialize()
  34457. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34458. __decorate([
  34459. BABYLON.serialize()
  34460. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34461. __decorate([
  34462. BABYLON.serialize()
  34463. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34464. __decorate([
  34465. BABYLON.serialize()
  34466. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34467. return FreeCameraKeyboardMoveInput;
  34468. }());
  34469. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34470. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34471. })(BABYLON || (BABYLON = {}));
  34472. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34473. var BABYLON;
  34474. (function (BABYLON) {
  34475. var FreeCameraInputsManager = (function (_super) {
  34476. __extends(FreeCameraInputsManager, _super);
  34477. function FreeCameraInputsManager(camera) {
  34478. return _super.call(this, camera) || this;
  34479. }
  34480. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34481. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34482. return this;
  34483. };
  34484. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34485. if (touchEnabled === void 0) { touchEnabled = true; }
  34486. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34487. return this;
  34488. };
  34489. FreeCameraInputsManager.prototype.addGamepad = function () {
  34490. this.add(new BABYLON.FreeCameraGamepadInput());
  34491. return this;
  34492. };
  34493. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34494. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34495. return this;
  34496. };
  34497. FreeCameraInputsManager.prototype.addTouch = function () {
  34498. this.add(new BABYLON.FreeCameraTouchInput());
  34499. return this;
  34500. };
  34501. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34502. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34503. return this;
  34504. };
  34505. return FreeCameraInputsManager;
  34506. }(BABYLON.CameraInputsManager));
  34507. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34508. })(BABYLON || (BABYLON = {}));
  34509. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34510. /// <reference path="babylon.camera.ts" />
  34511. var BABYLON;
  34512. (function (BABYLON) {
  34513. var TargetCamera = (function (_super) {
  34514. __extends(TargetCamera, _super);
  34515. function TargetCamera(name, position, scene) {
  34516. var _this = _super.call(this, name, position, scene) || this;
  34517. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34518. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34519. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34520. _this.speed = 2.0;
  34521. _this.noRotationConstraint = false;
  34522. _this.lockedTarget = null;
  34523. _this._currentTarget = BABYLON.Vector3.Zero();
  34524. _this._viewMatrix = BABYLON.Matrix.Zero();
  34525. _this._camMatrix = BABYLON.Matrix.Zero();
  34526. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34527. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34528. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34529. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34530. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34531. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34532. _this._tempMatrix = BABYLON.Matrix.Zero();
  34533. return _this;
  34534. }
  34535. TargetCamera.prototype.getFrontPosition = function (distance) {
  34536. var direction = this.getTarget().subtract(this.position);
  34537. direction.normalize();
  34538. direction.scaleInPlace(distance);
  34539. return this.globalPosition.add(direction);
  34540. };
  34541. TargetCamera.prototype._getLockedTargetPosition = function () {
  34542. if (!this.lockedTarget) {
  34543. return null;
  34544. }
  34545. if (this.lockedTarget.absolutePosition) {
  34546. this.lockedTarget.computeWorldMatrix();
  34547. }
  34548. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34549. };
  34550. TargetCamera.prototype.storeState = function () {
  34551. this._storedPosition = this.position.clone();
  34552. this._storedRotation = this.rotation.clone();
  34553. if (this.rotationQuaternion) {
  34554. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34555. }
  34556. return _super.prototype.storeState.call(this);
  34557. };
  34558. /**
  34559. * Restored camera state. You must call storeState() first
  34560. */
  34561. TargetCamera.prototype._restoreStateValues = function () {
  34562. if (!_super.prototype._restoreStateValues.call(this)) {
  34563. return false;
  34564. }
  34565. this.position = this._storedPosition.clone();
  34566. this.rotation = this._storedRotation.clone();
  34567. if (this.rotationQuaternion) {
  34568. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34569. }
  34570. this.cameraDirection.copyFromFloats(0, 0, 0);
  34571. this.cameraRotation.copyFromFloats(0, 0);
  34572. return true;
  34573. };
  34574. // Cache
  34575. TargetCamera.prototype._initCache = function () {
  34576. _super.prototype._initCache.call(this);
  34577. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34578. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34579. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34580. };
  34581. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34582. if (!ignoreParentClass) {
  34583. _super.prototype._updateCache.call(this);
  34584. }
  34585. var lockedTargetPosition = this._getLockedTargetPosition();
  34586. if (!lockedTargetPosition) {
  34587. this._cache.lockedTarget = null;
  34588. }
  34589. else {
  34590. if (!this._cache.lockedTarget) {
  34591. this._cache.lockedTarget = lockedTargetPosition.clone();
  34592. }
  34593. else {
  34594. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34595. }
  34596. }
  34597. this._cache.rotation.copyFrom(this.rotation);
  34598. if (this.rotationQuaternion)
  34599. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34600. };
  34601. // Synchronized
  34602. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34603. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34604. return false;
  34605. }
  34606. var lockedTargetPosition = this._getLockedTargetPosition();
  34607. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34608. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34609. };
  34610. // Methods
  34611. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34612. var engine = this.getEngine();
  34613. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34614. };
  34615. // Target
  34616. TargetCamera.prototype.setTarget = function (target) {
  34617. this.upVector.normalize();
  34618. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34619. this._camMatrix.invert();
  34620. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34621. var vDir = target.subtract(this.position);
  34622. if (vDir.x >= 0.0) {
  34623. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34624. }
  34625. else {
  34626. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34627. }
  34628. this.rotation.z = 0;
  34629. if (isNaN(this.rotation.x)) {
  34630. this.rotation.x = 0;
  34631. }
  34632. if (isNaN(this.rotation.y)) {
  34633. this.rotation.y = 0;
  34634. }
  34635. if (isNaN(this.rotation.z)) {
  34636. this.rotation.z = 0;
  34637. }
  34638. if (this.rotationQuaternion) {
  34639. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34640. }
  34641. };
  34642. /**
  34643. * Return the current target position of the camera. This value is expressed in local space.
  34644. */
  34645. TargetCamera.prototype.getTarget = function () {
  34646. return this._currentTarget;
  34647. };
  34648. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34649. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34650. };
  34651. TargetCamera.prototype._updatePosition = function () {
  34652. if (this.parent) {
  34653. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34654. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34655. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34656. return;
  34657. }
  34658. this.position.addInPlace(this.cameraDirection);
  34659. };
  34660. TargetCamera.prototype._checkInputs = function () {
  34661. var needToMove = this._decideIfNeedsToMove();
  34662. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34663. // Move
  34664. if (needToMove) {
  34665. this._updatePosition();
  34666. }
  34667. // Rotate
  34668. if (needToRotate) {
  34669. this.rotation.x += this.cameraRotation.x;
  34670. this.rotation.y += this.cameraRotation.y;
  34671. //rotate, if quaternion is set and rotation was used
  34672. if (this.rotationQuaternion) {
  34673. var len = this.rotation.lengthSquared();
  34674. if (len) {
  34675. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34676. }
  34677. }
  34678. if (!this.noRotationConstraint) {
  34679. var limit = (Math.PI / 2) * 0.95;
  34680. if (this.rotation.x > limit)
  34681. this.rotation.x = limit;
  34682. if (this.rotation.x < -limit)
  34683. this.rotation.x = -limit;
  34684. }
  34685. }
  34686. // Inertia
  34687. if (needToMove) {
  34688. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34689. this.cameraDirection.x = 0;
  34690. }
  34691. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34692. this.cameraDirection.y = 0;
  34693. }
  34694. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34695. this.cameraDirection.z = 0;
  34696. }
  34697. this.cameraDirection.scaleInPlace(this.inertia);
  34698. }
  34699. if (needToRotate) {
  34700. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34701. this.cameraRotation.x = 0;
  34702. }
  34703. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34704. this.cameraRotation.y = 0;
  34705. }
  34706. this.cameraRotation.scaleInPlace(this.inertia);
  34707. }
  34708. _super.prototype._checkInputs.call(this);
  34709. };
  34710. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34711. if (this.rotationQuaternion) {
  34712. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34713. //update the up vector!
  34714. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34715. }
  34716. else {
  34717. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34718. }
  34719. };
  34720. TargetCamera.prototype._getViewMatrix = function () {
  34721. if (!this.lockedTarget) {
  34722. // Compute
  34723. this._updateCameraRotationMatrix();
  34724. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34725. // Computing target and final matrix
  34726. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34727. }
  34728. else {
  34729. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34730. }
  34731. if (this.getScene().useRightHandedSystem) {
  34732. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34733. }
  34734. else {
  34735. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34736. }
  34737. return this._viewMatrix;
  34738. };
  34739. /**
  34740. * @override
  34741. * Override Camera.createRigCamera
  34742. */
  34743. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34744. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34745. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34746. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34747. if (!this.rotationQuaternion) {
  34748. this.rotationQuaternion = new BABYLON.Quaternion();
  34749. }
  34750. rigCamera._cameraRigParams = {};
  34751. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34752. }
  34753. return rigCamera;
  34754. }
  34755. return null;
  34756. };
  34757. /**
  34758. * @override
  34759. * Override Camera._updateRigCameras
  34760. */
  34761. TargetCamera.prototype._updateRigCameras = function () {
  34762. var camLeft = this._rigCameras[0];
  34763. var camRight = this._rigCameras[1];
  34764. switch (this.cameraRigMode) {
  34765. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34766. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34768. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34769. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34770. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34771. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34772. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34773. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34774. camLeft.setTarget(this.getTarget());
  34775. camRight.setTarget(this.getTarget());
  34776. break;
  34777. case BABYLON.Camera.RIG_MODE_VR:
  34778. if (camLeft.rotationQuaternion) {
  34779. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34780. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34781. }
  34782. else {
  34783. camLeft.rotation.copyFrom(this.rotation);
  34784. camRight.rotation.copyFrom(this.rotation);
  34785. }
  34786. camLeft.position.copyFrom(this.position);
  34787. camRight.position.copyFrom(this.position);
  34788. break;
  34789. }
  34790. _super.prototype._updateRigCameras.call(this);
  34791. };
  34792. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34793. if (!this._rigCamTransformMatrix) {
  34794. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34795. }
  34796. var target = this.getTarget();
  34797. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34798. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34799. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34800. };
  34801. TargetCamera.prototype.getClassName = function () {
  34802. return "TargetCamera";
  34803. };
  34804. __decorate([
  34805. BABYLON.serializeAsVector3()
  34806. ], TargetCamera.prototype, "rotation", void 0);
  34807. __decorate([
  34808. BABYLON.serialize()
  34809. ], TargetCamera.prototype, "speed", void 0);
  34810. __decorate([
  34811. BABYLON.serializeAsMeshReference("lockedTargetId")
  34812. ], TargetCamera.prototype, "lockedTarget", void 0);
  34813. return TargetCamera;
  34814. }(BABYLON.Camera));
  34815. BABYLON.TargetCamera = TargetCamera;
  34816. })(BABYLON || (BABYLON = {}));
  34817. //# sourceMappingURL=babylon.targetCamera.js.map
  34818. var BABYLON;
  34819. (function (BABYLON) {
  34820. var FreeCamera = (function (_super) {
  34821. __extends(FreeCamera, _super);
  34822. function FreeCamera(name, position, scene) {
  34823. var _this = _super.call(this, name, position, scene) || this;
  34824. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34825. _this.checkCollisions = false;
  34826. _this.applyGravity = false;
  34827. _this._needMoveForGravity = false;
  34828. _this._oldPosition = BABYLON.Vector3.Zero();
  34829. _this._diffPosition = BABYLON.Vector3.Zero();
  34830. _this._newPosition = BABYLON.Vector3.Zero();
  34831. // Collisions
  34832. _this._collisionMask = -1;
  34833. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34834. if (collidedMesh === void 0) { collidedMesh = null; }
  34835. //TODO move this to the collision coordinator!
  34836. if (_this.getScene().workerCollisions)
  34837. newPosition.multiplyInPlace(_this._collider.radius);
  34838. var updatePosition = function (newPos) {
  34839. _this._newPosition.copyFrom(newPos);
  34840. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34841. var oldPosition = _this.position.clone();
  34842. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34843. _this.position.addInPlace(_this._diffPosition);
  34844. if (_this.onCollide && collidedMesh) {
  34845. _this.onCollide(collidedMesh);
  34846. }
  34847. }
  34848. };
  34849. updatePosition(newPosition);
  34850. };
  34851. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34852. _this.inputs.addKeyboard().addMouse();
  34853. return _this;
  34854. }
  34855. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34856. //-- begin properties for backward compatibility for inputs
  34857. get: function () {
  34858. var mouse = this.inputs.attached["mouse"];
  34859. if (mouse)
  34860. return mouse.angularSensibility;
  34861. },
  34862. set: function (value) {
  34863. var mouse = this.inputs.attached["mouse"];
  34864. if (mouse)
  34865. mouse.angularSensibility = value;
  34866. },
  34867. enumerable: true,
  34868. configurable: true
  34869. });
  34870. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34871. get: function () {
  34872. var keyboard = this.inputs.attached["keyboard"];
  34873. if (keyboard)
  34874. return keyboard.keysUp;
  34875. },
  34876. set: function (value) {
  34877. var keyboard = this.inputs.attached["keyboard"];
  34878. if (keyboard)
  34879. keyboard.keysUp = value;
  34880. },
  34881. enumerable: true,
  34882. configurable: true
  34883. });
  34884. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34885. get: function () {
  34886. var keyboard = this.inputs.attached["keyboard"];
  34887. if (keyboard)
  34888. return keyboard.keysDown;
  34889. },
  34890. set: function (value) {
  34891. var keyboard = this.inputs.attached["keyboard"];
  34892. if (keyboard)
  34893. keyboard.keysDown = value;
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34899. get: function () {
  34900. var keyboard = this.inputs.attached["keyboard"];
  34901. if (keyboard)
  34902. return keyboard.keysLeft;
  34903. },
  34904. set: function (value) {
  34905. var keyboard = this.inputs.attached["keyboard"];
  34906. if (keyboard)
  34907. keyboard.keysLeft = value;
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34913. get: function () {
  34914. var keyboard = this.inputs.attached["keyboard"];
  34915. if (keyboard)
  34916. return keyboard.keysRight;
  34917. },
  34918. set: function (value) {
  34919. var keyboard = this.inputs.attached["keyboard"];
  34920. if (keyboard)
  34921. keyboard.keysRight = value;
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. // Controls
  34927. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34928. this.inputs.attachElement(element, noPreventDefault);
  34929. };
  34930. FreeCamera.prototype.detachControl = function (element) {
  34931. this.inputs.detachElement(element);
  34932. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34933. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34934. };
  34935. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34936. get: function () {
  34937. return this._collisionMask;
  34938. },
  34939. set: function (mask) {
  34940. this._collisionMask = !isNaN(mask) ? mask : -1;
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. FreeCamera.prototype._collideWithWorld = function (displacement) {
  34946. var globalPosition;
  34947. if (this.parent) {
  34948. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34949. }
  34950. else {
  34951. globalPosition = this.position;
  34952. }
  34953. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34954. if (!this._collider) {
  34955. this._collider = new BABYLON.Collider();
  34956. }
  34957. this._collider.radius = this.ellipsoid;
  34958. this._collider.collisionMask = this._collisionMask;
  34959. //no need for clone, as long as gravity is not on.
  34960. var actualDisplacement = displacement;
  34961. //add gravity to the direction to prevent the dual-collision checking
  34962. if (this.applyGravity) {
  34963. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34964. actualDisplacement = displacement.add(this.getScene().gravity);
  34965. }
  34966. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34967. };
  34968. FreeCamera.prototype._checkInputs = function () {
  34969. if (!this._localDirection) {
  34970. this._localDirection = BABYLON.Vector3.Zero();
  34971. this._transformedDirection = BABYLON.Vector3.Zero();
  34972. }
  34973. this.inputs.checkInputs();
  34974. _super.prototype._checkInputs.call(this);
  34975. };
  34976. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34977. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34978. };
  34979. FreeCamera.prototype._updatePosition = function () {
  34980. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34981. this._collideWithWorld(this.cameraDirection);
  34982. }
  34983. else {
  34984. _super.prototype._updatePosition.call(this);
  34985. }
  34986. };
  34987. FreeCamera.prototype.dispose = function () {
  34988. this.inputs.clear();
  34989. _super.prototype.dispose.call(this);
  34990. };
  34991. FreeCamera.prototype.getClassName = function () {
  34992. return "FreeCamera";
  34993. };
  34994. __decorate([
  34995. BABYLON.serializeAsVector3()
  34996. ], FreeCamera.prototype, "ellipsoid", void 0);
  34997. __decorate([
  34998. BABYLON.serialize()
  34999. ], FreeCamera.prototype, "checkCollisions", void 0);
  35000. __decorate([
  35001. BABYLON.serialize()
  35002. ], FreeCamera.prototype, "applyGravity", void 0);
  35003. return FreeCamera;
  35004. }(BABYLON.TargetCamera));
  35005. BABYLON.FreeCamera = FreeCamera;
  35006. })(BABYLON || (BABYLON = {}));
  35007. //# sourceMappingURL=babylon.freeCamera.js.map
  35008. var BABYLON;
  35009. (function (BABYLON) {
  35010. var ArcRotateCameraKeyboardMoveInput = (function () {
  35011. function ArcRotateCameraKeyboardMoveInput() {
  35012. this._keys = [];
  35013. this.keysUp = [38];
  35014. this.keysDown = [40];
  35015. this.keysLeft = [37];
  35016. this.keysRight = [39];
  35017. this.keysReset = [111];
  35018. this.panningSensibility = 50.0;
  35019. }
  35020. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35021. var _this = this;
  35022. if (this._onCanvasBlurObserver) {
  35023. return;
  35024. }
  35025. this._scene = this.camera.getScene();
  35026. this._engine = this._scene.getEngine();
  35027. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35028. _this._keys = [];
  35029. });
  35030. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35031. var evt = info.event;
  35032. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35033. _this._ctrlPressed = evt.ctrlKey;
  35034. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35035. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35036. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35037. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35038. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35039. var index = _this._keys.indexOf(evt.keyCode);
  35040. if (index === -1) {
  35041. _this._keys.push(evt.keyCode);
  35042. }
  35043. if (evt.preventDefault) {
  35044. if (!noPreventDefault) {
  35045. evt.preventDefault();
  35046. }
  35047. }
  35048. }
  35049. }
  35050. else {
  35051. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35052. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35053. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35054. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35055. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35056. var index = _this._keys.indexOf(evt.keyCode);
  35057. if (index >= 0) {
  35058. _this._keys.splice(index, 1);
  35059. }
  35060. if (evt.preventDefault) {
  35061. if (!noPreventDefault) {
  35062. evt.preventDefault();
  35063. }
  35064. }
  35065. }
  35066. }
  35067. });
  35068. };
  35069. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35070. if (this._scene) {
  35071. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35072. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35073. this._onKeyboardObserver = null;
  35074. this._onCanvasBlurObserver = null;
  35075. }
  35076. this._keys = [];
  35077. };
  35078. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35079. if (this._onKeyboardObserver) {
  35080. var camera = this.camera;
  35081. for (var index = 0; index < this._keys.length; index++) {
  35082. var keyCode = this._keys[index];
  35083. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35084. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35085. camera.inertialPanningX -= 1 / this.panningSensibility;
  35086. }
  35087. else {
  35088. camera.inertialAlphaOffset -= 0.01;
  35089. }
  35090. }
  35091. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35092. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35093. camera.inertialPanningY += 1 / this.panningSensibility;
  35094. }
  35095. else {
  35096. camera.inertialBetaOffset -= 0.01;
  35097. }
  35098. }
  35099. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35100. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35101. camera.inertialPanningX += 1 / this.panningSensibility;
  35102. }
  35103. else {
  35104. camera.inertialAlphaOffset += 0.01;
  35105. }
  35106. }
  35107. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35108. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35109. camera.inertialPanningY -= 1 / this.panningSensibility;
  35110. }
  35111. else {
  35112. camera.inertialBetaOffset += 0.01;
  35113. }
  35114. }
  35115. else if (this.keysReset.indexOf(keyCode) !== -1) {
  35116. camera.restoreState();
  35117. }
  35118. }
  35119. }
  35120. };
  35121. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  35122. return "ArcRotateCameraKeyboardMoveInput";
  35123. };
  35124. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35125. return "keyboard";
  35126. };
  35127. __decorate([
  35128. BABYLON.serialize()
  35129. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35130. __decorate([
  35131. BABYLON.serialize()
  35132. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35133. __decorate([
  35134. BABYLON.serialize()
  35135. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35136. __decorate([
  35137. BABYLON.serialize()
  35138. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35139. __decorate([
  35140. BABYLON.serialize()
  35141. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35142. __decorate([
  35143. BABYLON.serialize()
  35144. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35145. return ArcRotateCameraKeyboardMoveInput;
  35146. }());
  35147. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35148. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35149. })(BABYLON || (BABYLON = {}));
  35150. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35151. var BABYLON;
  35152. (function (BABYLON) {
  35153. var ArcRotateCameraMouseWheelInput = (function () {
  35154. function ArcRotateCameraMouseWheelInput() {
  35155. this.wheelPrecision = 3.0;
  35156. }
  35157. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35158. var _this = this;
  35159. this._wheel = function (p, s) {
  35160. //sanity check - this should be a PointerWheel event.
  35161. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35162. return;
  35163. var event = p.event;
  35164. var delta = 0;
  35165. if (event.wheelDelta) {
  35166. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35167. }
  35168. else if (event.detail) {
  35169. delta = -event.detail / _this.wheelPrecision;
  35170. }
  35171. if (delta)
  35172. _this.camera.inertialRadiusOffset += delta;
  35173. if (event.preventDefault) {
  35174. if (!noPreventDefault) {
  35175. event.preventDefault();
  35176. }
  35177. }
  35178. };
  35179. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35180. };
  35181. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35182. if (this._observer && element) {
  35183. this.camera.getScene().onPointerObservable.remove(this._observer);
  35184. this._observer = null;
  35185. this._wheel = null;
  35186. }
  35187. };
  35188. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35189. return "ArcRotateCameraMouseWheelInput";
  35190. };
  35191. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35192. return "mousewheel";
  35193. };
  35194. __decorate([
  35195. BABYLON.serialize()
  35196. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35197. return ArcRotateCameraMouseWheelInput;
  35198. }());
  35199. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35200. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35201. })(BABYLON || (BABYLON = {}));
  35202. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35203. var BABYLON;
  35204. (function (BABYLON) {
  35205. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35206. var ArcRotateCameraPointersInput = (function () {
  35207. function ArcRotateCameraPointersInput() {
  35208. this.buttons = [0, 1, 2];
  35209. this.angularSensibilityX = 1000.0;
  35210. this.angularSensibilityY = 1000.0;
  35211. this.pinchPrecision = 6.0;
  35212. this.panningSensibility = 50.0;
  35213. this.multiTouchPanning = true;
  35214. this._isPanClick = false;
  35215. this.pinchInwards = true;
  35216. }
  35217. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35218. var _this = this;
  35219. var engine = this.camera.getEngine();
  35220. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35221. var pointA, pointB;
  35222. var previousPinchSquaredDistance = 0;
  35223. var previousPinchDistance = 0;
  35224. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false };
  35225. this._pointerInput = function (p, s) {
  35226. var evt = p.event;
  35227. if (engine.isInVRExclusivePointerMode) {
  35228. return;
  35229. }
  35230. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35231. return;
  35232. }
  35233. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35234. try {
  35235. evt.srcElement.setPointerCapture(evt.pointerId);
  35236. }
  35237. catch (e) {
  35238. //Nothing to do with the error. Execution will continue.
  35239. }
  35240. // Manage panning with pan button click
  35241. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  35242. // manage pointers
  35243. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35244. if (pointA === undefined) {
  35245. pointA = cacheSoloPointer;
  35246. }
  35247. else if (pointB === undefined) {
  35248. pointB = cacheSoloPointer;
  35249. }
  35250. if (!noPreventDefault) {
  35251. evt.preventDefault();
  35252. element.focus();
  35253. }
  35254. }
  35255. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35256. _this.camera.restoreState();
  35257. }
  35258. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35259. try {
  35260. evt.srcElement.releasePointerCapture(evt.pointerId);
  35261. }
  35262. catch (e) {
  35263. //Nothing to do with the error.
  35264. }
  35265. cacheSoloPointer = null;
  35266. previousPinchSquaredDistance = 0;
  35267. previousPinchDistance = 0;
  35268. previousMultiTouchPanPosition.isPaning = false;
  35269. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35270. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35271. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35272. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35273. pointA = pointB = undefined;
  35274. if (!noPreventDefault) {
  35275. evt.preventDefault();
  35276. }
  35277. }
  35278. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35279. if (!noPreventDefault) {
  35280. evt.preventDefault();
  35281. }
  35282. // One button down
  35283. if (pointA && pointB === undefined) {
  35284. if (_this.panningSensibility !== 0 &&
  35285. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35286. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35287. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35288. }
  35289. else {
  35290. var offsetX = evt.clientX - cacheSoloPointer.x;
  35291. var offsetY = evt.clientY - cacheSoloPointer.y;
  35292. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35293. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35294. }
  35295. cacheSoloPointer.x = evt.clientX;
  35296. cacheSoloPointer.y = evt.clientY;
  35297. }
  35298. else if (pointA && pointB) {
  35299. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35300. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35301. ed.x = evt.clientX;
  35302. ed.y = evt.clientY;
  35303. var direction = _this.pinchInwards ? 1 : -1;
  35304. var distX = pointA.x - pointB.x;
  35305. var distY = pointA.y - pointB.y;
  35306. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35307. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35308. if (previousPinchSquaredDistance === 0) {
  35309. previousPinchSquaredDistance = pinchSquaredDistance;
  35310. previousPinchDistance = pinchDistance;
  35311. return;
  35312. }
  35313. if (pinchDistance > _this.camera.panMaxFingersDistance || Math.abs(pinchDistance - previousPinchDistance) > _this.camera.pinchToPanMaxDistance) {
  35314. _this.camera
  35315. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35316. (_this.pinchPrecision *
  35317. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35318. direction);
  35319. previousMultiTouchPanPosition.isPaning = false;
  35320. }
  35321. else {
  35322. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35323. if (!previousMultiTouchPanPosition.isPaning) {
  35324. previousMultiTouchPanPosition.isPaning = true;
  35325. previousMultiTouchPanPosition.x = ed.x;
  35326. previousMultiTouchPanPosition.y = ed.y;
  35327. return;
  35328. }
  35329. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / _this.panningSensibility;
  35330. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / _this.panningSensibility;
  35331. }
  35332. }
  35333. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35334. previousMultiTouchPanPosition.x = ed.x;
  35335. previousMultiTouchPanPosition.y = ed.y;
  35336. }
  35337. previousPinchSquaredDistance = pinchSquaredDistance;
  35338. previousPinchDistance = pinchDistance;
  35339. }
  35340. }
  35341. };
  35342. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35343. this._onContextMenu = function (evt) {
  35344. evt.preventDefault();
  35345. };
  35346. if (!this.camera._useCtrlForPanning) {
  35347. element.addEventListener("contextmenu", this._onContextMenu, false);
  35348. }
  35349. this._onLostFocus = function () {
  35350. //this._keys = [];
  35351. pointA = pointB = undefined;
  35352. previousPinchSquaredDistance = 0;
  35353. previousPinchDistance = 0;
  35354. previousMultiTouchPanPosition.isPaning = false;
  35355. cacheSoloPointer = null;
  35356. };
  35357. this._onMouseMove = function (evt) {
  35358. if (!engine.isPointerLock) {
  35359. return;
  35360. }
  35361. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35362. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35363. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35364. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35365. if (!noPreventDefault) {
  35366. evt.preventDefault();
  35367. }
  35368. };
  35369. this._onGestureStart = function (e) {
  35370. if (window.MSGesture === undefined) {
  35371. return;
  35372. }
  35373. if (!_this._MSGestureHandler) {
  35374. _this._MSGestureHandler = new MSGesture();
  35375. _this._MSGestureHandler.target = element;
  35376. }
  35377. _this._MSGestureHandler.addPointer(e.pointerId);
  35378. };
  35379. this._onGesture = function (e) {
  35380. _this.camera.radius *= e.scale;
  35381. if (e.preventDefault) {
  35382. if (!noPreventDefault) {
  35383. e.stopPropagation();
  35384. e.preventDefault();
  35385. }
  35386. }
  35387. };
  35388. element.addEventListener("mousemove", this._onMouseMove, false);
  35389. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35390. element.addEventListener("MSGestureChange", this._onGesture, false);
  35391. BABYLON.Tools.RegisterTopRootEvents([
  35392. { name: "blur", handler: this._onLostFocus }
  35393. ]);
  35394. };
  35395. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35396. BABYLON.Tools.UnregisterTopRootEvents([
  35397. { name: "blur", handler: this._onLostFocus }
  35398. ]);
  35399. if (element && this._observer) {
  35400. this.camera.getScene().onPointerObservable.remove(this._observer);
  35401. this._observer = null;
  35402. element.removeEventListener("contextmenu", this._onContextMenu);
  35403. element.removeEventListener("mousemove", this._onMouseMove);
  35404. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35405. element.removeEventListener("MSGestureChange", this._onGesture);
  35406. this._isPanClick = false;
  35407. this.pinchInwards = true;
  35408. this._onMouseMove = null;
  35409. this._onGestureStart = null;
  35410. this._onGesture = null;
  35411. this._MSGestureHandler = null;
  35412. this._onLostFocus = null;
  35413. this._onContextMenu = null;
  35414. }
  35415. };
  35416. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35417. return "ArcRotateCameraPointersInput";
  35418. };
  35419. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35420. return "pointers";
  35421. };
  35422. __decorate([
  35423. BABYLON.serialize()
  35424. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35425. __decorate([
  35426. BABYLON.serialize()
  35427. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35428. __decorate([
  35429. BABYLON.serialize()
  35430. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35431. __decorate([
  35432. BABYLON.serialize()
  35433. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35434. __decorate([
  35435. BABYLON.serialize()
  35436. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35437. __decorate([
  35438. BABYLON.serialize()
  35439. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35440. return ArcRotateCameraPointersInput;
  35441. }());
  35442. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35443. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35444. })(BABYLON || (BABYLON = {}));
  35445. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35446. /// <reference path="babylon.targetCamera.ts" />
  35447. /// <reference path="..\Tools\babylon.tools.ts" />
  35448. var BABYLON;
  35449. (function (BABYLON) {
  35450. var ArcRotateCamera = (function (_super) {
  35451. __extends(ArcRotateCamera, _super);
  35452. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35453. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35454. _this.inertialAlphaOffset = 0;
  35455. _this.inertialBetaOffset = 0;
  35456. _this.inertialRadiusOffset = 0;
  35457. _this.lowerAlphaLimit = null;
  35458. _this.upperAlphaLimit = null;
  35459. _this.lowerBetaLimit = 0.01;
  35460. _this.upperBetaLimit = Math.PI;
  35461. _this.lowerRadiusLimit = null;
  35462. _this.upperRadiusLimit = null;
  35463. _this.inertialPanningX = 0;
  35464. _this.inertialPanningY = 0;
  35465. _this.pinchToPanMaxDistance = 3;
  35466. _this.panMaxFingersDistance = 100;
  35467. _this.panningDistanceLimit = null;
  35468. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35469. _this.panningInertia = 0.9;
  35470. //-- end properties for backward compatibility for inputs
  35471. _this.zoomOnFactor = 1;
  35472. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35473. _this.allowUpsideDown = true;
  35474. _this._viewMatrix = new BABYLON.Matrix();
  35475. // Panning
  35476. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35477. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35478. _this.checkCollisions = false;
  35479. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35480. _this._previousPosition = BABYLON.Vector3.Zero();
  35481. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35482. _this._newPosition = BABYLON.Vector3.Zero();
  35483. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35484. if (collidedMesh === void 0) { collidedMesh = null; }
  35485. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35486. newPosition.multiplyInPlace(_this._collider.radius);
  35487. }
  35488. if (!collidedMesh) {
  35489. _this._previousPosition.copyFrom(_this.position);
  35490. }
  35491. else {
  35492. _this.setPosition(newPosition);
  35493. if (_this.onCollide) {
  35494. _this.onCollide(collidedMesh);
  35495. }
  35496. }
  35497. // Recompute because of constraints
  35498. var cosa = Math.cos(_this.alpha);
  35499. var sina = Math.sin(_this.alpha);
  35500. var cosb = Math.cos(_this.beta);
  35501. var sinb = Math.sin(_this.beta);
  35502. if (sinb === 0) {
  35503. sinb = 0.0001;
  35504. }
  35505. var target = _this._getTargetPosition();
  35506. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35507. _this.position.copyFrom(_this._newPosition);
  35508. var up = _this.upVector;
  35509. if (_this.allowUpsideDown && _this.beta < 0) {
  35510. up = up.clone();
  35511. up = up.negate();
  35512. }
  35513. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35514. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35515. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35516. _this._collisionTriggered = false;
  35517. };
  35518. _this._target = BABYLON.Vector3.Zero();
  35519. if (target) {
  35520. _this.setTarget(target);
  35521. }
  35522. _this.alpha = alpha;
  35523. _this.beta = beta;
  35524. _this.radius = radius;
  35525. _this.getViewMatrix();
  35526. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35527. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35528. return _this;
  35529. }
  35530. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35531. get: function () {
  35532. return this._target;
  35533. },
  35534. set: function (value) {
  35535. this.setTarget(value);
  35536. },
  35537. enumerable: true,
  35538. configurable: true
  35539. });
  35540. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35541. //-- begin properties for backward compatibility for inputs
  35542. get: function () {
  35543. var pointers = this.inputs.attached["pointers"];
  35544. if (pointers)
  35545. return pointers.angularSensibilityX;
  35546. },
  35547. set: function (value) {
  35548. var pointers = this.inputs.attached["pointers"];
  35549. if (pointers) {
  35550. pointers.angularSensibilityX = value;
  35551. }
  35552. },
  35553. enumerable: true,
  35554. configurable: true
  35555. });
  35556. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35557. get: function () {
  35558. var pointers = this.inputs.attached["pointers"];
  35559. if (pointers)
  35560. return pointers.angularSensibilityY;
  35561. },
  35562. set: function (value) {
  35563. var pointers = this.inputs.attached["pointers"];
  35564. if (pointers) {
  35565. pointers.angularSensibilityY = value;
  35566. }
  35567. },
  35568. enumerable: true,
  35569. configurable: true
  35570. });
  35571. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35572. get: function () {
  35573. var pointers = this.inputs.attached["pointers"];
  35574. if (pointers)
  35575. return pointers.pinchPrecision;
  35576. },
  35577. set: function (value) {
  35578. var pointers = this.inputs.attached["pointers"];
  35579. if (pointers) {
  35580. pointers.pinchPrecision = value;
  35581. }
  35582. },
  35583. enumerable: true,
  35584. configurable: true
  35585. });
  35586. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35587. get: function () {
  35588. var pointers = this.inputs.attached["pointers"];
  35589. if (pointers)
  35590. return pointers.panningSensibility;
  35591. },
  35592. set: function (value) {
  35593. var pointers = this.inputs.attached["pointers"];
  35594. if (pointers) {
  35595. pointers.panningSensibility = value;
  35596. }
  35597. },
  35598. enumerable: true,
  35599. configurable: true
  35600. });
  35601. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35602. get: function () {
  35603. var keyboard = this.inputs.attached["keyboard"];
  35604. if (keyboard)
  35605. return keyboard.keysUp;
  35606. },
  35607. set: function (value) {
  35608. var keyboard = this.inputs.attached["keyboard"];
  35609. if (keyboard)
  35610. keyboard.keysUp = value;
  35611. },
  35612. enumerable: true,
  35613. configurable: true
  35614. });
  35615. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35616. get: function () {
  35617. var keyboard = this.inputs.attached["keyboard"];
  35618. if (keyboard)
  35619. return keyboard.keysDown;
  35620. },
  35621. set: function (value) {
  35622. var keyboard = this.inputs.attached["keyboard"];
  35623. if (keyboard)
  35624. keyboard.keysDown = value;
  35625. },
  35626. enumerable: true,
  35627. configurable: true
  35628. });
  35629. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35630. get: function () {
  35631. var keyboard = this.inputs.attached["keyboard"];
  35632. if (keyboard)
  35633. return keyboard.keysLeft;
  35634. },
  35635. set: function (value) {
  35636. var keyboard = this.inputs.attached["keyboard"];
  35637. if (keyboard)
  35638. keyboard.keysLeft = value;
  35639. },
  35640. enumerable: true,
  35641. configurable: true
  35642. });
  35643. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35644. get: function () {
  35645. var keyboard = this.inputs.attached["keyboard"];
  35646. if (keyboard)
  35647. return keyboard.keysRight;
  35648. },
  35649. set: function (value) {
  35650. var keyboard = this.inputs.attached["keyboard"];
  35651. if (keyboard)
  35652. keyboard.keysRight = value;
  35653. },
  35654. enumerable: true,
  35655. configurable: true
  35656. });
  35657. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35658. get: function () {
  35659. var mousewheel = this.inputs.attached["mousewheel"];
  35660. if (mousewheel)
  35661. return mousewheel.wheelPrecision;
  35662. },
  35663. set: function (value) {
  35664. var mousewheel = this.inputs.attached["mousewheel"];
  35665. if (mousewheel)
  35666. mousewheel.wheelPrecision = value;
  35667. },
  35668. enumerable: true,
  35669. configurable: true
  35670. });
  35671. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35672. get: function () {
  35673. return this._bouncingBehavior;
  35674. },
  35675. enumerable: true,
  35676. configurable: true
  35677. });
  35678. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35679. get: function () {
  35680. return this._bouncingBehavior != null;
  35681. },
  35682. set: function (value) {
  35683. if (value === this.useBouncingBehavior) {
  35684. return;
  35685. }
  35686. if (value) {
  35687. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35688. this.addBehavior(this._bouncingBehavior);
  35689. }
  35690. else {
  35691. this.removeBehavior(this._bouncingBehavior);
  35692. this._bouncingBehavior = null;
  35693. }
  35694. },
  35695. enumerable: true,
  35696. configurable: true
  35697. });
  35698. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35699. get: function () {
  35700. return this._framingBehavior;
  35701. },
  35702. enumerable: true,
  35703. configurable: true
  35704. });
  35705. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35706. get: function () {
  35707. return this._framingBehavior != null;
  35708. },
  35709. set: function (value) {
  35710. if (value === this.useFramingBehavior) {
  35711. return;
  35712. }
  35713. if (value) {
  35714. this._framingBehavior = new BABYLON.FramingBehavior();
  35715. this.addBehavior(this._framingBehavior);
  35716. }
  35717. else {
  35718. this.removeBehavior(this._framingBehavior);
  35719. this._framingBehavior = null;
  35720. }
  35721. },
  35722. enumerable: true,
  35723. configurable: true
  35724. });
  35725. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35726. get: function () {
  35727. return this._autoRotationBehavior;
  35728. },
  35729. enumerable: true,
  35730. configurable: true
  35731. });
  35732. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35733. get: function () {
  35734. return this._autoRotationBehavior != null;
  35735. },
  35736. set: function (value) {
  35737. if (value === this.useAutoRotationBehavior) {
  35738. return;
  35739. }
  35740. if (value) {
  35741. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35742. this.addBehavior(this._autoRotationBehavior);
  35743. }
  35744. else {
  35745. this.removeBehavior(this._autoRotationBehavior);
  35746. this._autoRotationBehavior = null;
  35747. }
  35748. },
  35749. enumerable: true,
  35750. configurable: true
  35751. });
  35752. // Cache
  35753. ArcRotateCamera.prototype._initCache = function () {
  35754. _super.prototype._initCache.call(this);
  35755. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35756. this._cache.alpha = undefined;
  35757. this._cache.beta = undefined;
  35758. this._cache.radius = undefined;
  35759. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35760. };
  35761. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35762. if (!ignoreParentClass) {
  35763. _super.prototype._updateCache.call(this);
  35764. }
  35765. this._cache._target.copyFrom(this._getTargetPosition());
  35766. this._cache.alpha = this.alpha;
  35767. this._cache.beta = this.beta;
  35768. this._cache.radius = this.radius;
  35769. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35770. };
  35771. ArcRotateCamera.prototype._getTargetPosition = function () {
  35772. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35773. var pos = this._targetHost.getAbsolutePosition();
  35774. if (this._targetBoundingCenter) {
  35775. pos.addToRef(this._targetBoundingCenter, this._target);
  35776. }
  35777. else {
  35778. this._target.copyFrom(pos);
  35779. }
  35780. }
  35781. var lockedTargetPosition = this._getLockedTargetPosition();
  35782. if (lockedTargetPosition) {
  35783. return lockedTargetPosition;
  35784. }
  35785. return this._target;
  35786. };
  35787. ArcRotateCamera.prototype.storeState = function () {
  35788. this._storedAlpha = this.alpha;
  35789. this._storedBeta = this.beta;
  35790. this._storedRadius = this.radius;
  35791. this._storedTarget = this._getTargetPosition().clone();
  35792. return _super.prototype.storeState.call(this);
  35793. };
  35794. /**
  35795. * Restored camera state. You must call storeState() first
  35796. */
  35797. ArcRotateCamera.prototype._restoreStateValues = function () {
  35798. if (!_super.prototype._restoreStateValues.call(this)) {
  35799. return false;
  35800. }
  35801. this.alpha = this._storedAlpha;
  35802. this.beta = this._storedBeta;
  35803. this.radius = this._storedRadius;
  35804. this.setTarget(this._storedTarget);
  35805. this.inertialAlphaOffset = 0;
  35806. this.inertialBetaOffset = 0;
  35807. this.inertialRadiusOffset = 0;
  35808. this.inertialPanningX = 0;
  35809. this.inertialPanningY = 0;
  35810. return true;
  35811. };
  35812. // Synchronized
  35813. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35814. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35815. return false;
  35816. return this._cache._target.equals(this._getTargetPosition())
  35817. && this._cache.alpha === this.alpha
  35818. && this._cache.beta === this.beta
  35819. && this._cache.radius === this.radius
  35820. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35821. };
  35822. // Methods
  35823. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35824. var _this = this;
  35825. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35826. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35827. this._useCtrlForPanning = useCtrlForPanning;
  35828. this._panningMouseButton = panningMouseButton;
  35829. this.inputs.attachElement(element, noPreventDefault);
  35830. this._reset = function () {
  35831. _this.inertialAlphaOffset = 0;
  35832. _this.inertialBetaOffset = 0;
  35833. _this.inertialRadiusOffset = 0;
  35834. _this.inertialPanningX = 0;
  35835. _this.inertialPanningY = 0;
  35836. };
  35837. };
  35838. ArcRotateCamera.prototype.detachControl = function (element) {
  35839. this.inputs.detachElement(element);
  35840. if (this._reset) {
  35841. this._reset();
  35842. }
  35843. };
  35844. ArcRotateCamera.prototype._checkInputs = function () {
  35845. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35846. if (this._collisionTriggered) {
  35847. return;
  35848. }
  35849. this.inputs.checkInputs();
  35850. // Inertia
  35851. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35852. if (this.getScene().useRightHandedSystem) {
  35853. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35854. }
  35855. else {
  35856. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35857. }
  35858. this.beta += this.inertialBetaOffset;
  35859. this.radius -= this.inertialRadiusOffset;
  35860. this.inertialAlphaOffset *= this.inertia;
  35861. this.inertialBetaOffset *= this.inertia;
  35862. this.inertialRadiusOffset *= this.inertia;
  35863. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35864. this.inertialAlphaOffset = 0;
  35865. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35866. this.inertialBetaOffset = 0;
  35867. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35868. this.inertialRadiusOffset = 0;
  35869. }
  35870. // Panning inertia
  35871. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35872. if (!this._localDirection) {
  35873. this._localDirection = BABYLON.Vector3.Zero();
  35874. this._transformedDirection = BABYLON.Vector3.Zero();
  35875. }
  35876. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35877. this._localDirection.multiplyInPlace(this.panningAxis);
  35878. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35879. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35880. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35881. if (!this.panningAxis.y) {
  35882. this._transformedDirection.y = 0;
  35883. }
  35884. if (!this._targetHost) {
  35885. if (this.panningDistanceLimit) {
  35886. this._transformedDirection.addInPlace(this._target);
  35887. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  35888. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  35889. this._target.copyFrom(this._transformedDirection);
  35890. }
  35891. }
  35892. else {
  35893. this._target.addInPlace(this._transformedDirection);
  35894. }
  35895. }
  35896. this.inertialPanningX *= this.panningInertia;
  35897. this.inertialPanningY *= this.panningInertia;
  35898. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35899. this.inertialPanningX = 0;
  35900. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35901. this.inertialPanningY = 0;
  35902. }
  35903. // Limits
  35904. this._checkLimits();
  35905. _super.prototype._checkInputs.call(this);
  35906. };
  35907. ArcRotateCamera.prototype._checkLimits = function () {
  35908. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35909. if (this.allowUpsideDown && this.beta > Math.PI) {
  35910. this.beta = this.beta - (2 * Math.PI);
  35911. }
  35912. }
  35913. else {
  35914. if (this.beta < this.lowerBetaLimit) {
  35915. this.beta = this.lowerBetaLimit;
  35916. }
  35917. }
  35918. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35919. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35920. this.beta = this.beta + (2 * Math.PI);
  35921. }
  35922. }
  35923. else {
  35924. if (this.beta > this.upperBetaLimit) {
  35925. this.beta = this.upperBetaLimit;
  35926. }
  35927. }
  35928. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35929. this.alpha = this.lowerAlphaLimit;
  35930. }
  35931. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35932. this.alpha = this.upperAlphaLimit;
  35933. }
  35934. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35935. this.radius = this.lowerRadiusLimit;
  35936. }
  35937. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35938. this.radius = this.upperRadiusLimit;
  35939. }
  35940. };
  35941. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35942. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35943. this.radius = radiusv3.length();
  35944. if (this.radius === 0) {
  35945. this.radius = 0.0001; // Just to avoid division by zero
  35946. }
  35947. // Alpha
  35948. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35949. if (radiusv3.z < 0) {
  35950. this.alpha = 2 * Math.PI - this.alpha;
  35951. }
  35952. // Beta
  35953. this.beta = Math.acos(radiusv3.y / this.radius);
  35954. this._checkLimits();
  35955. };
  35956. ArcRotateCamera.prototype.setPosition = function (position) {
  35957. if (this.position.equals(position)) {
  35958. return;
  35959. }
  35960. this.position.copyFrom(position);
  35961. this.rebuildAnglesAndRadius();
  35962. };
  35963. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35964. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35965. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35966. if (target.getBoundingInfo) {
  35967. if (toBoundingCenter) {
  35968. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35969. }
  35970. else {
  35971. this._targetBoundingCenter = null;
  35972. }
  35973. this._targetHost = target;
  35974. this._target = this._getTargetPosition();
  35975. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35976. }
  35977. else {
  35978. var newTarget = target;
  35979. var currentTarget = this._getTargetPosition();
  35980. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35981. return;
  35982. }
  35983. this._targetHost = null;
  35984. this._target = newTarget;
  35985. this._targetBoundingCenter = null;
  35986. this.onMeshTargetChangedObservable.notifyObservers(null);
  35987. }
  35988. this.rebuildAnglesAndRadius();
  35989. };
  35990. ArcRotateCamera.prototype._getViewMatrix = function () {
  35991. // Compute
  35992. var cosa = Math.cos(this.alpha);
  35993. var sina = Math.sin(this.alpha);
  35994. var cosb = Math.cos(this.beta);
  35995. var sinb = Math.sin(this.beta);
  35996. if (sinb === 0) {
  35997. sinb = 0.0001;
  35998. }
  35999. var target = this._getTargetPosition();
  36000. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  36001. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  36002. if (!this._collider) {
  36003. this._collider = new BABYLON.Collider();
  36004. }
  36005. this._collider.radius = this.collisionRadius;
  36006. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  36007. this._collisionTriggered = true;
  36008. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36009. }
  36010. else {
  36011. this.position.copyFrom(this._newPosition);
  36012. var up = this.upVector;
  36013. if (this.allowUpsideDown && sinb < 0) {
  36014. up = up.clone();
  36015. up = up.negate();
  36016. }
  36017. if (this.getScene().useRightHandedSystem) {
  36018. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  36019. }
  36020. else {
  36021. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  36022. }
  36023. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  36024. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  36025. }
  36026. this._currentTarget = target;
  36027. return this._viewMatrix;
  36028. };
  36029. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  36030. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36031. meshes = meshes || this.getScene().meshes;
  36032. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  36033. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  36034. this.radius = distance * this.zoomOnFactor;
  36035. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  36036. };
  36037. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  36038. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36039. var meshesOrMinMaxVector;
  36040. var distance;
  36041. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  36042. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  36043. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  36044. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  36045. }
  36046. else {
  36047. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  36048. distance = meshesOrMinMaxVectorAndDistance.distance;
  36049. }
  36050. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  36051. if (!doNotUpdateMaxZ) {
  36052. this.maxZ = distance * 2;
  36053. }
  36054. };
  36055. /**
  36056. * @override
  36057. * Override Camera.createRigCamera
  36058. */
  36059. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36060. var alphaShift;
  36061. switch (this.cameraRigMode) {
  36062. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36063. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36064. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36065. case BABYLON.Camera.RIG_MODE_VR:
  36066. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  36067. break;
  36068. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36069. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  36070. break;
  36071. }
  36072. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  36073. rigCam._cameraRigParams = {};
  36074. return rigCam;
  36075. };
  36076. /**
  36077. * @override
  36078. * Override Camera._updateRigCameras
  36079. */
  36080. ArcRotateCamera.prototype._updateRigCameras = function () {
  36081. var camLeft = this._rigCameras[0];
  36082. var camRight = this._rigCameras[1];
  36083. camLeft.beta = camRight.beta = this.beta;
  36084. camLeft.radius = camRight.radius = this.radius;
  36085. switch (this.cameraRigMode) {
  36086. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36087. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36088. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36089. case BABYLON.Camera.RIG_MODE_VR:
  36090. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36091. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36092. break;
  36093. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36094. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36095. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36096. break;
  36097. }
  36098. _super.prototype._updateRigCameras.call(this);
  36099. };
  36100. ArcRotateCamera.prototype.dispose = function () {
  36101. this.inputs.clear();
  36102. _super.prototype.dispose.call(this);
  36103. };
  36104. ArcRotateCamera.prototype.getClassName = function () {
  36105. return "ArcRotateCamera";
  36106. };
  36107. __decorate([
  36108. BABYLON.serialize()
  36109. ], ArcRotateCamera.prototype, "alpha", void 0);
  36110. __decorate([
  36111. BABYLON.serialize()
  36112. ], ArcRotateCamera.prototype, "beta", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], ArcRotateCamera.prototype, "radius", void 0);
  36116. __decorate([
  36117. BABYLON.serializeAsVector3("target")
  36118. ], ArcRotateCamera.prototype, "_target", void 0);
  36119. __decorate([
  36120. BABYLON.serialize()
  36121. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  36122. __decorate([
  36123. BABYLON.serialize()
  36124. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  36125. __decorate([
  36126. BABYLON.serialize()
  36127. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36128. __decorate([
  36129. BABYLON.serialize()
  36130. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36131. __decorate([
  36132. BABYLON.serialize()
  36133. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36134. __decorate([
  36135. BABYLON.serialize()
  36136. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36143. __decorate([
  36144. BABYLON.serialize()
  36145. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36146. __decorate([
  36147. BABYLON.serialize()
  36148. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36149. __decorate([
  36150. BABYLON.serialize()
  36151. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36152. __decorate([
  36153. BABYLON.serialize()
  36154. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36155. __decorate([
  36156. BABYLON.serialize()
  36157. ], ArcRotateCamera.prototype, "panMaxFingersDistance", void 0);
  36158. __decorate([
  36159. BABYLON.serialize()
  36160. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36161. __decorate([
  36162. BABYLON.serializeAsVector3()
  36163. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36164. __decorate([
  36165. BABYLON.serialize()
  36166. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36167. __decorate([
  36168. BABYLON.serialize()
  36169. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36170. __decorate([
  36171. BABYLON.serialize()
  36172. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36173. return ArcRotateCamera;
  36174. }(BABYLON.TargetCamera));
  36175. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36176. })(BABYLON || (BABYLON = {}));
  36177. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36178. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36179. var BABYLON;
  36180. (function (BABYLON) {
  36181. var ArcRotateCameraInputsManager = (function (_super) {
  36182. __extends(ArcRotateCameraInputsManager, _super);
  36183. function ArcRotateCameraInputsManager(camera) {
  36184. return _super.call(this, camera) || this;
  36185. }
  36186. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36187. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36188. return this;
  36189. };
  36190. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36191. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36192. return this;
  36193. };
  36194. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36195. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36196. return this;
  36197. };
  36198. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36199. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36200. return this;
  36201. };
  36202. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36203. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36204. return this;
  36205. };
  36206. return ArcRotateCameraInputsManager;
  36207. }(BABYLON.CameraInputsManager));
  36208. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36209. })(BABYLON || (BABYLON = {}));
  36210. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36211. var BABYLON;
  36212. (function (BABYLON) {
  36213. var HemisphericLight = (function (_super) {
  36214. __extends(HemisphericLight, _super);
  36215. /**
  36216. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36217. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36218. * The HemisphericLight can't cast shadows.
  36219. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36220. */
  36221. function HemisphericLight(name, direction, scene) {
  36222. var _this = _super.call(this, name, scene) || this;
  36223. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36224. _this.direction = direction || BABYLON.Vector3.Up();
  36225. return _this;
  36226. }
  36227. HemisphericLight.prototype._buildUniformLayout = function () {
  36228. this._uniformBuffer.addUniform("vLightData", 4);
  36229. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36230. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36231. this._uniformBuffer.addUniform("vLightGround", 3);
  36232. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36233. this._uniformBuffer.addUniform("depthValues", 2);
  36234. this._uniformBuffer.create();
  36235. };
  36236. /**
  36237. * Returns the string "HemisphericLight".
  36238. */
  36239. HemisphericLight.prototype.getClassName = function () {
  36240. return "HemisphericLight";
  36241. };
  36242. /**
  36243. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36244. * Returns the updated direction.
  36245. */
  36246. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36247. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36248. return this.direction;
  36249. };
  36250. HemisphericLight.prototype.getShadowGenerator = function () {
  36251. return null;
  36252. };
  36253. /**
  36254. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36255. * Returns the HemisphericLight.
  36256. */
  36257. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36258. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36259. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36260. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36261. return this;
  36262. };
  36263. HemisphericLight.prototype._getWorldMatrix = function () {
  36264. if (!this._worldMatrix) {
  36265. this._worldMatrix = BABYLON.Matrix.Identity();
  36266. }
  36267. return this._worldMatrix;
  36268. };
  36269. /**
  36270. * Returns the integer 3.
  36271. */
  36272. HemisphericLight.prototype.getTypeID = function () {
  36273. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36274. };
  36275. __decorate([
  36276. BABYLON.serializeAsColor3()
  36277. ], HemisphericLight.prototype, "groundColor", void 0);
  36278. __decorate([
  36279. BABYLON.serializeAsVector3()
  36280. ], HemisphericLight.prototype, "direction", void 0);
  36281. return HemisphericLight;
  36282. }(BABYLON.Light));
  36283. BABYLON.HemisphericLight = HemisphericLight;
  36284. })(BABYLON || (BABYLON = {}));
  36285. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36286. var BABYLON;
  36287. (function (BABYLON) {
  36288. var ShadowLight = (function (_super) {
  36289. __extends(ShadowLight, _super);
  36290. function ShadowLight() {
  36291. var _this = _super !== null && _super.apply(this, arguments) || this;
  36292. _this._needProjectionMatrixCompute = true;
  36293. return _this;
  36294. }
  36295. Object.defineProperty(ShadowLight.prototype, "direction", {
  36296. get: function () {
  36297. return this._direction;
  36298. },
  36299. set: function (value) {
  36300. this._direction = value;
  36301. },
  36302. enumerable: true,
  36303. configurable: true
  36304. });
  36305. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36306. get: function () {
  36307. return this._shadowMinZ;
  36308. },
  36309. set: function (value) {
  36310. this._shadowMinZ = value;
  36311. this.forceProjectionMatrixCompute();
  36312. },
  36313. enumerable: true,
  36314. configurable: true
  36315. });
  36316. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36317. get: function () {
  36318. return this._shadowMaxZ;
  36319. },
  36320. set: function (value) {
  36321. this._shadowMaxZ = value;
  36322. this.forceProjectionMatrixCompute();
  36323. },
  36324. enumerable: true,
  36325. configurable: true
  36326. });
  36327. /**
  36328. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36329. */
  36330. ShadowLight.prototype.computeTransformedInformation = function () {
  36331. if (this.parent && this.parent.getWorldMatrix) {
  36332. if (!this.transformedPosition) {
  36333. this.transformedPosition = BABYLON.Vector3.Zero();
  36334. }
  36335. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36336. // In case the direction is present.
  36337. if (this.direction) {
  36338. if (!this.transformedDirection) {
  36339. this.transformedDirection = BABYLON.Vector3.Zero();
  36340. }
  36341. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36342. }
  36343. return true;
  36344. }
  36345. return false;
  36346. };
  36347. /**
  36348. * Return the depth scale used for the shadow map.
  36349. */
  36350. ShadowLight.prototype.getDepthScale = function () {
  36351. return 50.0;
  36352. };
  36353. /**
  36354. * Returns the light direction (Vector3) for any passed face index.
  36355. */
  36356. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36357. return this.transformedDirection ? this.transformedDirection : this.direction;
  36358. };
  36359. /**
  36360. * Returns the DirectionalLight absolute position in the World.
  36361. */
  36362. ShadowLight.prototype.getAbsolutePosition = function () {
  36363. return this.transformedPosition ? this.transformedPosition : this.position;
  36364. };
  36365. /**
  36366. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36367. * Returns the updated DirectionalLight direction (Vector3).
  36368. */
  36369. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36370. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36371. return this.direction;
  36372. };
  36373. /**
  36374. * Returns the light rotation (Vector3).
  36375. */
  36376. ShadowLight.prototype.getRotation = function () {
  36377. this.direction.normalize();
  36378. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36379. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36380. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36381. };
  36382. /**
  36383. * Boolean : false by default.
  36384. */
  36385. ShadowLight.prototype.needCube = function () {
  36386. return false;
  36387. };
  36388. /**
  36389. * Specifies wether or not the projection matrix should be recomputed this frame.
  36390. */
  36391. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36392. return this._needProjectionMatrixCompute;
  36393. };
  36394. /**
  36395. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36396. */
  36397. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36398. this._needProjectionMatrixCompute = true;
  36399. };
  36400. /**
  36401. * Get the world matrix of the sahdow lights.
  36402. */
  36403. ShadowLight.prototype._getWorldMatrix = function () {
  36404. if (!this._worldMatrix) {
  36405. this._worldMatrix = BABYLON.Matrix.Identity();
  36406. }
  36407. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36408. return this._worldMatrix;
  36409. };
  36410. /**
  36411. * Gets the minZ used for shadow according to both the scene and the light.
  36412. * @param activeCamera
  36413. */
  36414. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36415. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36416. };
  36417. /**
  36418. * Gets the maxZ used for shadow according to both the scene and the light.
  36419. * @param activeCamera
  36420. */
  36421. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36422. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36423. };
  36424. /**
  36425. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36426. * Returns the light.
  36427. */
  36428. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36429. if (this.customProjectionMatrixBuilder) {
  36430. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36431. }
  36432. else {
  36433. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36434. }
  36435. return this;
  36436. };
  36437. __decorate([
  36438. BABYLON.serializeAsVector3()
  36439. ], ShadowLight.prototype, "position", void 0);
  36440. __decorate([
  36441. BABYLON.serializeAsVector3()
  36442. ], ShadowLight.prototype, "direction", null);
  36443. __decorate([
  36444. BABYLON.serialize()
  36445. ], ShadowLight.prototype, "shadowMinZ", null);
  36446. __decorate([
  36447. BABYLON.serialize()
  36448. ], ShadowLight.prototype, "shadowMaxZ", null);
  36449. return ShadowLight;
  36450. }(BABYLON.Light));
  36451. BABYLON.ShadowLight = ShadowLight;
  36452. })(BABYLON || (BABYLON = {}));
  36453. //# sourceMappingURL=babylon.shadowLight.js.map
  36454. var BABYLON;
  36455. (function (BABYLON) {
  36456. var PointLight = (function (_super) {
  36457. __extends(PointLight, _super);
  36458. /**
  36459. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36460. * A PointLight emits the light in every direction.
  36461. * It can cast shadows.
  36462. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36463. * ```javascript
  36464. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36465. * ```
  36466. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36467. */
  36468. function PointLight(name, position, scene) {
  36469. var _this = _super.call(this, name, scene) || this;
  36470. _this._shadowAngle = Math.PI / 2;
  36471. _this.position = position;
  36472. return _this;
  36473. }
  36474. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36475. /**
  36476. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36477. * This specifies what angle the shadow will use to be created.
  36478. *
  36479. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36480. */
  36481. get: function () {
  36482. return this._shadowAngle;
  36483. },
  36484. /**
  36485. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36486. * This specifies what angle the shadow will use to be created.
  36487. *
  36488. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36489. */
  36490. set: function (value) {
  36491. this._shadowAngle = value;
  36492. this.forceProjectionMatrixCompute();
  36493. },
  36494. enumerable: true,
  36495. configurable: true
  36496. });
  36497. Object.defineProperty(PointLight.prototype, "direction", {
  36498. get: function () {
  36499. return this._direction;
  36500. },
  36501. /**
  36502. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36503. */
  36504. set: function (value) {
  36505. var previousNeedCube = this.needCube();
  36506. this._direction = value;
  36507. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36508. this._shadowGenerator.recreateShadowMap();
  36509. }
  36510. },
  36511. enumerable: true,
  36512. configurable: true
  36513. });
  36514. /**
  36515. * Returns the string "PointLight"
  36516. */
  36517. PointLight.prototype.getClassName = function () {
  36518. return "PointLight";
  36519. };
  36520. /**
  36521. * Returns the integer 0.
  36522. */
  36523. PointLight.prototype.getTypeID = function () {
  36524. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36525. };
  36526. /**
  36527. * Specifies wether or not the shadowmap should be a cube texture.
  36528. */
  36529. PointLight.prototype.needCube = function () {
  36530. return !this.direction;
  36531. };
  36532. /**
  36533. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36534. */
  36535. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36536. if (this.direction) {
  36537. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36538. }
  36539. else {
  36540. switch (faceIndex) {
  36541. case 0:
  36542. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36543. case 1:
  36544. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36545. case 2:
  36546. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36547. case 3:
  36548. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36549. case 4:
  36550. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36551. case 5:
  36552. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36553. }
  36554. }
  36555. return BABYLON.Vector3.Zero();
  36556. };
  36557. /**
  36558. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36559. * - fov = PI / 2
  36560. * - aspect ratio : 1.0
  36561. * - z-near and far equal to the active camera minZ and maxZ.
  36562. * Returns the PointLight.
  36563. */
  36564. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36565. var activeCamera = this.getScene().activeCamera;
  36566. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36567. };
  36568. PointLight.prototype._buildUniformLayout = function () {
  36569. this._uniformBuffer.addUniform("vLightData", 4);
  36570. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36571. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36572. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36573. this._uniformBuffer.addUniform("depthValues", 2);
  36574. this._uniformBuffer.create();
  36575. };
  36576. /**
  36577. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36578. * Returns the PointLight.
  36579. */
  36580. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36581. if (this.computeTransformedInformation()) {
  36582. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36583. return this;
  36584. }
  36585. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36586. return this;
  36587. };
  36588. __decorate([
  36589. BABYLON.serialize()
  36590. ], PointLight.prototype, "shadowAngle", null);
  36591. return PointLight;
  36592. }(BABYLON.ShadowLight));
  36593. BABYLON.PointLight = PointLight;
  36594. })(BABYLON || (BABYLON = {}));
  36595. //# sourceMappingURL=babylon.pointLight.js.map
  36596. /// <reference path="babylon.light.ts" />
  36597. var BABYLON;
  36598. (function (BABYLON) {
  36599. var DirectionalLight = (function (_super) {
  36600. __extends(DirectionalLight, _super);
  36601. /**
  36602. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36603. * The directional light is emitted from everywhere in the given direction.
  36604. * It can cast shawdows.
  36605. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36606. */
  36607. function DirectionalLight(name, direction, scene) {
  36608. var _this = _super.call(this, name, scene) || this;
  36609. _this._shadowFrustumSize = 0;
  36610. _this._shadowOrthoScale = 0.5;
  36611. _this.autoUpdateExtends = true;
  36612. // Cache
  36613. _this._orthoLeft = Number.MAX_VALUE;
  36614. _this._orthoRight = Number.MIN_VALUE;
  36615. _this._orthoTop = Number.MIN_VALUE;
  36616. _this._orthoBottom = Number.MAX_VALUE;
  36617. _this.position = direction.scale(-1.0);
  36618. _this.direction = direction;
  36619. return _this;
  36620. }
  36621. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36622. /**
  36623. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36624. */
  36625. get: function () {
  36626. return this._shadowFrustumSize;
  36627. },
  36628. /**
  36629. * Specifies a fix frustum size for the shadow generation.
  36630. */
  36631. set: function (value) {
  36632. this._shadowFrustumSize = value;
  36633. this.forceProjectionMatrixCompute();
  36634. },
  36635. enumerable: true,
  36636. configurable: true
  36637. });
  36638. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36639. get: function () {
  36640. return this._shadowOrthoScale;
  36641. },
  36642. set: function (value) {
  36643. this._shadowOrthoScale = value;
  36644. this.forceProjectionMatrixCompute();
  36645. },
  36646. enumerable: true,
  36647. configurable: true
  36648. });
  36649. /**
  36650. * Returns the string "DirectionalLight".
  36651. */
  36652. DirectionalLight.prototype.getClassName = function () {
  36653. return "DirectionalLight";
  36654. };
  36655. /**
  36656. * Returns the integer 1.
  36657. */
  36658. DirectionalLight.prototype.getTypeID = function () {
  36659. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36660. };
  36661. /**
  36662. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36663. * Returns the DirectionalLight Shadow projection matrix.
  36664. */
  36665. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36666. if (this.shadowFrustumSize > 0) {
  36667. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36668. }
  36669. else {
  36670. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36671. }
  36672. };
  36673. /**
  36674. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36675. * Returns the DirectionalLight Shadow projection matrix.
  36676. */
  36677. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36678. var activeCamera = this.getScene().activeCamera;
  36679. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36680. };
  36681. /**
  36682. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36683. * Returns the DirectionalLight Shadow projection matrix.
  36684. */
  36685. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36686. var activeCamera = this.getScene().activeCamera;
  36687. // Check extends
  36688. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36689. var tempVector3 = BABYLON.Vector3.Zero();
  36690. this._orthoLeft = Number.MAX_VALUE;
  36691. this._orthoRight = Number.MIN_VALUE;
  36692. this._orthoTop = Number.MIN_VALUE;
  36693. this._orthoBottom = Number.MAX_VALUE;
  36694. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36695. var mesh = renderList[meshIndex];
  36696. if (!mesh) {
  36697. continue;
  36698. }
  36699. var boundingInfo = mesh.getBoundingInfo();
  36700. if (!boundingInfo) {
  36701. continue;
  36702. }
  36703. var boundingBox = boundingInfo.boundingBox;
  36704. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36705. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36706. if (tempVector3.x < this._orthoLeft)
  36707. this._orthoLeft = tempVector3.x;
  36708. if (tempVector3.y < this._orthoBottom)
  36709. this._orthoBottom = tempVector3.y;
  36710. if (tempVector3.x > this._orthoRight)
  36711. this._orthoRight = tempVector3.x;
  36712. if (tempVector3.y > this._orthoTop)
  36713. this._orthoTop = tempVector3.y;
  36714. }
  36715. }
  36716. }
  36717. var xOffset = this._orthoRight - this._orthoLeft;
  36718. var yOffset = this._orthoTop - this._orthoBottom;
  36719. 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);
  36720. };
  36721. DirectionalLight.prototype._buildUniformLayout = function () {
  36722. this._uniformBuffer.addUniform("vLightData", 4);
  36723. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36724. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36725. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36726. this._uniformBuffer.addUniform("depthValues", 2);
  36727. this._uniformBuffer.create();
  36728. };
  36729. /**
  36730. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36731. * Returns the DirectionalLight.
  36732. */
  36733. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36734. if (this.computeTransformedInformation()) {
  36735. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36736. return this;
  36737. }
  36738. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36739. return this;
  36740. };
  36741. /**
  36742. * Gets the minZ used for shadow according to both the scene and the light.
  36743. *
  36744. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36745. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36746. * @param activeCamera
  36747. */
  36748. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36749. return 1;
  36750. };
  36751. /**
  36752. * Gets the maxZ used for shadow according to both the scene and the light.
  36753. *
  36754. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36755. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36756. * @param activeCamera
  36757. */
  36758. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36759. return 1;
  36760. };
  36761. __decorate([
  36762. BABYLON.serialize()
  36763. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36764. __decorate([
  36765. BABYLON.serialize()
  36766. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36767. __decorate([
  36768. BABYLON.serialize()
  36769. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36770. return DirectionalLight;
  36771. }(BABYLON.ShadowLight));
  36772. BABYLON.DirectionalLight = DirectionalLight;
  36773. })(BABYLON || (BABYLON = {}));
  36774. //# sourceMappingURL=babylon.directionalLight.js.map
  36775. var BABYLON;
  36776. (function (BABYLON) {
  36777. var SpotLight = (function (_super) {
  36778. __extends(SpotLight, _super);
  36779. /**
  36780. * Creates a SpotLight object in the scene with the passed parameters :
  36781. * - `position` (Vector3) is the initial SpotLight position,
  36782. * - `direction` (Vector3) is the initial SpotLight direction,
  36783. * - `angle` (float, in radians) is the spot light cone angle,
  36784. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36785. * A spot light is a simply light oriented cone.
  36786. * It can cast shadows.
  36787. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36788. */
  36789. function SpotLight(name, position, direction, angle, exponent, scene) {
  36790. var _this = _super.call(this, name, scene) || this;
  36791. _this.position = position;
  36792. _this.direction = direction;
  36793. _this.angle = angle;
  36794. _this.exponent = exponent;
  36795. return _this;
  36796. }
  36797. Object.defineProperty(SpotLight.prototype, "angle", {
  36798. get: function () {
  36799. return this._angle;
  36800. },
  36801. set: function (value) {
  36802. this._angle = value;
  36803. this.forceProjectionMatrixCompute();
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36809. get: function () {
  36810. return this._shadowAngleScale;
  36811. },
  36812. /**
  36813. * Allows scaling the angle of the light for shadow generation only.
  36814. */
  36815. set: function (value) {
  36816. this._shadowAngleScale = value;
  36817. this.forceProjectionMatrixCompute();
  36818. },
  36819. enumerable: true,
  36820. configurable: true
  36821. });
  36822. /**
  36823. * Returns the string "SpotLight".
  36824. */
  36825. SpotLight.prototype.getClassName = function () {
  36826. return "SpotLight";
  36827. };
  36828. /**
  36829. * Returns the integer 2.
  36830. */
  36831. SpotLight.prototype.getTypeID = function () {
  36832. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36833. };
  36834. /**
  36835. * 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.
  36836. * Returns the SpotLight.
  36837. */
  36838. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36839. var activeCamera = this.getScene().activeCamera;
  36840. this._shadowAngleScale = this._shadowAngleScale || 1;
  36841. var angle = this._shadowAngleScale * this._angle;
  36842. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36843. };
  36844. SpotLight.prototype._buildUniformLayout = function () {
  36845. this._uniformBuffer.addUniform("vLightData", 4);
  36846. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36847. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36848. this._uniformBuffer.addUniform("vLightDirection", 3);
  36849. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36850. this._uniformBuffer.addUniform("depthValues", 2);
  36851. this._uniformBuffer.create();
  36852. };
  36853. /**
  36854. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36855. * Return the SpotLight.
  36856. */
  36857. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36858. var normalizeDirection;
  36859. if (this.computeTransformedInformation()) {
  36860. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36861. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36862. }
  36863. else {
  36864. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36865. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36866. }
  36867. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36868. return this;
  36869. };
  36870. __decorate([
  36871. BABYLON.serialize()
  36872. ], SpotLight.prototype, "angle", null);
  36873. __decorate([
  36874. BABYLON.serialize()
  36875. /**
  36876. * Allows scaling the angle of the light for shadow generation only.
  36877. */
  36878. ], SpotLight.prototype, "shadowAngleScale", null);
  36879. __decorate([
  36880. BABYLON.serialize()
  36881. ], SpotLight.prototype, "exponent", void 0);
  36882. return SpotLight;
  36883. }(BABYLON.ShadowLight));
  36884. BABYLON.SpotLight = SpotLight;
  36885. })(BABYLON || (BABYLON = {}));
  36886. //# sourceMappingURL=babylon.spotLight.js.map
  36887. var BABYLON;
  36888. (function (BABYLON) {
  36889. var AnimationRange = (function () {
  36890. function AnimationRange(name, from, to) {
  36891. this.name = name;
  36892. this.from = from;
  36893. this.to = to;
  36894. }
  36895. AnimationRange.prototype.clone = function () {
  36896. return new AnimationRange(this.name, this.from, this.to);
  36897. };
  36898. return AnimationRange;
  36899. }());
  36900. BABYLON.AnimationRange = AnimationRange;
  36901. /**
  36902. * Composed of a frame, and an action function
  36903. */
  36904. var AnimationEvent = (function () {
  36905. function AnimationEvent(frame, action, onlyOnce) {
  36906. this.frame = frame;
  36907. this.action = action;
  36908. this.onlyOnce = onlyOnce;
  36909. this.isDone = false;
  36910. }
  36911. return AnimationEvent;
  36912. }());
  36913. BABYLON.AnimationEvent = AnimationEvent;
  36914. var PathCursor = (function () {
  36915. function PathCursor(path) {
  36916. this.path = path;
  36917. this._onchange = new Array();
  36918. this.value = 0;
  36919. this.animations = new Array();
  36920. }
  36921. PathCursor.prototype.getPoint = function () {
  36922. var point = this.path.getPointAtLengthPosition(this.value);
  36923. return new BABYLON.Vector3(point.x, 0, point.y);
  36924. };
  36925. PathCursor.prototype.moveAhead = function (step) {
  36926. if (step === void 0) { step = 0.002; }
  36927. this.move(step);
  36928. return this;
  36929. };
  36930. PathCursor.prototype.moveBack = function (step) {
  36931. if (step === void 0) { step = 0.002; }
  36932. this.move(-step);
  36933. return this;
  36934. };
  36935. PathCursor.prototype.move = function (step) {
  36936. if (Math.abs(step) > 1) {
  36937. throw "step size should be less than 1.";
  36938. }
  36939. this.value += step;
  36940. this.ensureLimits();
  36941. this.raiseOnChange();
  36942. return this;
  36943. };
  36944. PathCursor.prototype.ensureLimits = function () {
  36945. while (this.value > 1) {
  36946. this.value -= 1;
  36947. }
  36948. while (this.value < 0) {
  36949. this.value += 1;
  36950. }
  36951. return this;
  36952. };
  36953. // used by animation engine
  36954. PathCursor.prototype.markAsDirty = function (propertyName) {
  36955. this.ensureLimits();
  36956. this.raiseOnChange();
  36957. return this;
  36958. };
  36959. PathCursor.prototype.raiseOnChange = function () {
  36960. var _this = this;
  36961. this._onchange.forEach(function (f) { return f(_this); });
  36962. return this;
  36963. };
  36964. PathCursor.prototype.onchange = function (f) {
  36965. this._onchange.push(f);
  36966. return this;
  36967. };
  36968. return PathCursor;
  36969. }());
  36970. BABYLON.PathCursor = PathCursor;
  36971. var Animation = (function () {
  36972. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36973. this.name = name;
  36974. this.targetProperty = targetProperty;
  36975. this.framePerSecond = framePerSecond;
  36976. this.dataType = dataType;
  36977. this.loopMode = loopMode;
  36978. this.enableBlending = enableBlending;
  36979. this._offsetsCache = {};
  36980. this._highLimitsCache = {};
  36981. this._stopped = false;
  36982. this._blendingFactor = 0;
  36983. // The set of event that will be linked to this animation
  36984. this._events = new Array();
  36985. this.blendingSpeed = 0.01;
  36986. this._ranges = {};
  36987. this.targetPropertyPath = targetProperty.split(".");
  36988. this.dataType = dataType;
  36989. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36990. }
  36991. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36992. var dataType = undefined;
  36993. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36994. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36995. }
  36996. else if (from instanceof BABYLON.Quaternion) {
  36997. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36998. }
  36999. else if (from instanceof BABYLON.Vector3) {
  37000. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  37001. }
  37002. else if (from instanceof BABYLON.Vector2) {
  37003. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  37004. }
  37005. else if (from instanceof BABYLON.Color3) {
  37006. dataType = Animation.ANIMATIONTYPE_COLOR3;
  37007. }
  37008. else if (from instanceof BABYLON.Size) {
  37009. dataType = Animation.ANIMATIONTYPE_SIZE;
  37010. }
  37011. if (dataType == undefined) {
  37012. return null;
  37013. }
  37014. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  37015. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  37016. animation.setKeys(keys);
  37017. if (easingFunction !== undefined) {
  37018. animation.setEasingFunction(easingFunction);
  37019. }
  37020. return animation;
  37021. };
  37022. /**
  37023. * Sets up an animation.
  37024. * @param property the property to animate
  37025. * @param animationType the animation type to apply
  37026. * @param easingFunction the easing function used in the animation
  37027. * @returns The created animation
  37028. */
  37029. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  37030. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37031. animation.setEasingFunction(easingFunction);
  37032. return animation;
  37033. };
  37034. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37035. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37036. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37037. };
  37038. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37039. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37040. node.animations.push(animation);
  37041. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37042. };
  37043. /**
  37044. * Transition property of the Camera to the target Value.
  37045. * @param property The property to transition
  37046. * @param targetValue The target Value of the property
  37047. * @param host The object where the property to animate belongs
  37048. * @param scene Scene used to run the animation
  37049. * @param frameRate Framerate (in frame/s) to use
  37050. * @param transition The transition type we want to use
  37051. * @param duration The duration of the animation, in milliseconds
  37052. * @param onAnimationEnd Call back trigger at the end of the animation.
  37053. */
  37054. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  37055. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  37056. if (duration <= 0) {
  37057. host[property] = targetValue;
  37058. if (onAnimationEnd) {
  37059. onAnimationEnd();
  37060. }
  37061. return;
  37062. }
  37063. var endFrame = frameRate * (duration / 1000);
  37064. transition.setKeys([{
  37065. frame: 0,
  37066. value: host[property].clone ? host[property].clone() : host[property]
  37067. },
  37068. {
  37069. frame: endFrame,
  37070. value: targetValue
  37071. }]);
  37072. if (!host.animations) {
  37073. host.animations = [];
  37074. }
  37075. host.animations.push(transition);
  37076. var animation = scene.beginAnimation(host, 0, endFrame, false);
  37077. animation.onAnimationEnd = onAnimationEnd;
  37078. return animation;
  37079. };
  37080. // Methods
  37081. /**
  37082. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  37083. */
  37084. Animation.prototype.toString = function (fullDetails) {
  37085. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  37086. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  37087. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  37088. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  37089. if (fullDetails) {
  37090. ret += ", Ranges: {";
  37091. var first = true;
  37092. for (var name in this._ranges) {
  37093. if (first) {
  37094. ret += ", ";
  37095. first = false;
  37096. }
  37097. ret += name;
  37098. }
  37099. ret += "}";
  37100. }
  37101. return ret;
  37102. };
  37103. /**
  37104. * Add an event to this animation.
  37105. */
  37106. Animation.prototype.addEvent = function (event) {
  37107. this._events.push(event);
  37108. };
  37109. /**
  37110. * Remove all events found at the given frame
  37111. * @param frame
  37112. */
  37113. Animation.prototype.removeEvents = function (frame) {
  37114. for (var index = 0; index < this._events.length; index++) {
  37115. if (this._events[index].frame === frame) {
  37116. this._events.splice(index, 1);
  37117. index--;
  37118. }
  37119. }
  37120. };
  37121. Animation.prototype.createRange = function (name, from, to) {
  37122. // check name not already in use; could happen for bones after serialized
  37123. if (!this._ranges[name]) {
  37124. this._ranges[name] = new AnimationRange(name, from, to);
  37125. }
  37126. };
  37127. Animation.prototype.deleteRange = function (name, deleteFrames) {
  37128. if (deleteFrames === void 0) { deleteFrames = true; }
  37129. if (this._ranges[name]) {
  37130. if (deleteFrames) {
  37131. var from = this._ranges[name].from;
  37132. var to = this._ranges[name].to;
  37133. // this loop MUST go high to low for multiple splices to work
  37134. for (var key = this._keys.length - 1; key >= 0; key--) {
  37135. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37136. this._keys.splice(key, 1);
  37137. }
  37138. }
  37139. }
  37140. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37141. }
  37142. };
  37143. Animation.prototype.getRange = function (name) {
  37144. return this._ranges[name];
  37145. };
  37146. Animation.prototype.reset = function () {
  37147. this._offsetsCache = {};
  37148. this._highLimitsCache = {};
  37149. this.currentFrame = 0;
  37150. this._blendingFactor = 0;
  37151. this._originalBlendValue = null;
  37152. };
  37153. Animation.prototype.isStopped = function () {
  37154. return this._stopped;
  37155. };
  37156. Animation.prototype.getKeys = function () {
  37157. return this._keys;
  37158. };
  37159. Animation.prototype.getHighestFrame = function () {
  37160. var ret = 0;
  37161. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37162. if (ret < this._keys[key].frame) {
  37163. ret = this._keys[key].frame;
  37164. }
  37165. }
  37166. return ret;
  37167. };
  37168. Animation.prototype.getEasingFunction = function () {
  37169. return this._easingFunction;
  37170. };
  37171. Animation.prototype.setEasingFunction = function (easingFunction) {
  37172. this._easingFunction = easingFunction;
  37173. };
  37174. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37175. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37176. };
  37177. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37178. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37179. };
  37180. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37181. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37182. };
  37183. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37184. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37185. };
  37186. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37187. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37188. };
  37189. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37190. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37191. };
  37192. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37193. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37194. };
  37195. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37196. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37197. };
  37198. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37199. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37200. };
  37201. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37202. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37203. };
  37204. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37205. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37206. };
  37207. Animation.prototype.clone = function () {
  37208. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37209. clone.enableBlending = this.enableBlending;
  37210. clone.blendingSpeed = this.blendingSpeed;
  37211. if (this._keys) {
  37212. clone.setKeys(this._keys);
  37213. }
  37214. if (this._ranges) {
  37215. clone._ranges = {};
  37216. for (var name in this._ranges) {
  37217. clone._ranges[name] = this._ranges[name].clone();
  37218. }
  37219. }
  37220. return clone;
  37221. };
  37222. Animation.prototype.setKeys = function (values) {
  37223. this._keys = values.slice(0);
  37224. this._offsetsCache = {};
  37225. this._highLimitsCache = {};
  37226. };
  37227. Animation.prototype._getKeyValue = function (value) {
  37228. if (typeof value === "function") {
  37229. return value();
  37230. }
  37231. return value;
  37232. };
  37233. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37234. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37235. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37236. }
  37237. this.currentFrame = currentFrame;
  37238. // Try to get a hash to find the right key
  37239. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  37240. if (this._keys[startKeyIndex].frame >= currentFrame) {
  37241. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  37242. startKeyIndex--;
  37243. }
  37244. }
  37245. for (var key = startKeyIndex; key < this._keys.length; key++) {
  37246. var endKey = this._keys[key + 1];
  37247. if (endKey.frame >= currentFrame) {
  37248. var startKey = this._keys[key];
  37249. var startValue = this._getKeyValue(startKey.value);
  37250. var endValue = this._getKeyValue(endKey.value);
  37251. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37252. var frameDelta = endKey.frame - startKey.frame;
  37253. // gradient : percent of currentFrame between the frame inf and the frame sup
  37254. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37255. // check for easingFunction and correction of gradient
  37256. if (this._easingFunction != null) {
  37257. gradient = this._easingFunction.ease(gradient);
  37258. }
  37259. switch (this.dataType) {
  37260. // Float
  37261. case Animation.ANIMATIONTYPE_FLOAT:
  37262. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  37263. switch (loopMode) {
  37264. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37265. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37266. return floatValue;
  37267. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37268. return offsetValue * repeatCount + floatValue;
  37269. }
  37270. break;
  37271. // Quaternion
  37272. case Animation.ANIMATIONTYPE_QUATERNION:
  37273. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  37274. switch (loopMode) {
  37275. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37276. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37277. return quatValue;
  37278. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37279. return quatValue.add(offsetValue.scale(repeatCount));
  37280. }
  37281. return quatValue;
  37282. // Vector3
  37283. case Animation.ANIMATIONTYPE_VECTOR3:
  37284. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  37285. switch (loopMode) {
  37286. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37287. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37288. return vec3Value;
  37289. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37290. return vec3Value.add(offsetValue.scale(repeatCount));
  37291. }
  37292. // Vector2
  37293. case Animation.ANIMATIONTYPE_VECTOR2:
  37294. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  37295. switch (loopMode) {
  37296. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37297. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37298. return vec2Value;
  37299. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37300. return vec2Value.add(offsetValue.scale(repeatCount));
  37301. }
  37302. // Size
  37303. case Animation.ANIMATIONTYPE_SIZE:
  37304. switch (loopMode) {
  37305. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37306. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37307. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  37308. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37309. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37310. }
  37311. // Color3
  37312. case Animation.ANIMATIONTYPE_COLOR3:
  37313. switch (loopMode) {
  37314. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37315. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37316. return this.color3InterpolateFunction(startValue, endValue, gradient);
  37317. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37318. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37319. }
  37320. // Matrix
  37321. case Animation.ANIMATIONTYPE_MATRIX:
  37322. switch (loopMode) {
  37323. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37324. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37325. if (Animation.AllowMatricesInterpolation) {
  37326. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  37327. }
  37328. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37329. return startValue;
  37330. }
  37331. default:
  37332. break;
  37333. }
  37334. break;
  37335. }
  37336. }
  37337. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  37338. };
  37339. Animation.prototype.setValue = function (currentValue, blend) {
  37340. if (blend === void 0) { blend = false; }
  37341. // Set value
  37342. var path;
  37343. var destination;
  37344. if (this.targetPropertyPath.length > 1) {
  37345. var property = this._target[this.targetPropertyPath[0]];
  37346. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  37347. property = property[this.targetPropertyPath[index]];
  37348. }
  37349. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  37350. destination = property;
  37351. }
  37352. else {
  37353. path = this.targetPropertyPath[0];
  37354. destination = this._target;
  37355. }
  37356. // Blending
  37357. if (this.enableBlending && this._blendingFactor <= 1.0) {
  37358. if (!this._originalBlendValue) {
  37359. if (destination[path].clone) {
  37360. this._originalBlendValue = destination[path].clone();
  37361. }
  37362. else {
  37363. this._originalBlendValue = destination[path];
  37364. }
  37365. }
  37366. if (this._originalBlendValue.prototype) {
  37367. if (this._originalBlendValue.prototype.Lerp) {
  37368. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37369. }
  37370. else {
  37371. destination[path] = currentValue;
  37372. }
  37373. }
  37374. else if (this._originalBlendValue.m) {
  37375. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37376. }
  37377. else {
  37378. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37379. }
  37380. this._blendingFactor += this.blendingSpeed;
  37381. }
  37382. else {
  37383. destination[path] = currentValue;
  37384. }
  37385. if (this._target.markAsDirty) {
  37386. this._target.markAsDirty(this.targetProperty);
  37387. }
  37388. };
  37389. Animation.prototype.goToFrame = function (frame) {
  37390. if (frame < this._keys[0].frame) {
  37391. frame = this._keys[0].frame;
  37392. }
  37393. else if (frame > this._keys[this._keys.length - 1].frame) {
  37394. frame = this._keys[this._keys.length - 1].frame;
  37395. }
  37396. var currentValue = this._interpolate(frame, 0, this.loopMode);
  37397. this.setValue(currentValue);
  37398. };
  37399. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37400. if (blend === void 0) { blend = false; }
  37401. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  37402. this._stopped = true;
  37403. return false;
  37404. }
  37405. var returnValue = true;
  37406. // Adding a start key at frame 0 if missing
  37407. if (this._keys[0].frame !== 0) {
  37408. var newKey = { frame: 0, value: this._keys[0].value };
  37409. this._keys.splice(0, 0, newKey);
  37410. }
  37411. // Check limits
  37412. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  37413. from = this._keys[0].frame;
  37414. }
  37415. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  37416. to = this._keys[this._keys.length - 1].frame;
  37417. }
  37418. //to and from cannot be the same key
  37419. if (from === to) {
  37420. from++;
  37421. }
  37422. // Compute ratio
  37423. var range = to - from;
  37424. var offsetValue;
  37425. // ratio represents the frame delta between from and to
  37426. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  37427. var highLimitValue = 0;
  37428. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37429. returnValue = false;
  37430. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  37431. }
  37432. else {
  37433. // Get max value if required
  37434. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  37435. var keyOffset = to.toString() + from.toString();
  37436. if (!this._offsetsCache[keyOffset]) {
  37437. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  37438. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  37439. switch (this.dataType) {
  37440. // Float
  37441. case Animation.ANIMATIONTYPE_FLOAT:
  37442. this._offsetsCache[keyOffset] = toValue - fromValue;
  37443. break;
  37444. // Quaternion
  37445. case Animation.ANIMATIONTYPE_QUATERNION:
  37446. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37447. break;
  37448. // Vector3
  37449. case Animation.ANIMATIONTYPE_VECTOR3:
  37450. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37451. // Vector2
  37452. case Animation.ANIMATIONTYPE_VECTOR2:
  37453. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37454. // Size
  37455. case Animation.ANIMATIONTYPE_SIZE:
  37456. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37457. // Color3
  37458. case Animation.ANIMATIONTYPE_COLOR3:
  37459. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37460. default:
  37461. break;
  37462. }
  37463. this._highLimitsCache[keyOffset] = toValue;
  37464. }
  37465. highLimitValue = this._highLimitsCache[keyOffset];
  37466. offsetValue = this._offsetsCache[keyOffset];
  37467. }
  37468. }
  37469. if (offsetValue === undefined) {
  37470. switch (this.dataType) {
  37471. // Float
  37472. case Animation.ANIMATIONTYPE_FLOAT:
  37473. offsetValue = 0;
  37474. break;
  37475. // Quaternion
  37476. case Animation.ANIMATIONTYPE_QUATERNION:
  37477. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37478. break;
  37479. // Vector3
  37480. case Animation.ANIMATIONTYPE_VECTOR3:
  37481. offsetValue = BABYLON.Vector3.Zero();
  37482. break;
  37483. // Vector2
  37484. case Animation.ANIMATIONTYPE_VECTOR2:
  37485. offsetValue = BABYLON.Vector2.Zero();
  37486. break;
  37487. // Size
  37488. case Animation.ANIMATIONTYPE_SIZE:
  37489. offsetValue = BABYLON.Size.Zero();
  37490. break;
  37491. // Color3
  37492. case Animation.ANIMATIONTYPE_COLOR3:
  37493. offsetValue = BABYLON.Color3.Black();
  37494. }
  37495. }
  37496. // Compute value
  37497. var repeatCount = (ratio / range) >> 0;
  37498. var currentFrame = returnValue ? from + ratio % range : to;
  37499. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  37500. // Set value
  37501. this.setValue(currentValue);
  37502. // Check events
  37503. for (var index = 0; index < this._events.length; index++) {
  37504. // Make sure current frame has passed event frame and that event frame is within the current range
  37505. // Also, handle both forward and reverse animations
  37506. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  37507. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  37508. var event = this._events[index];
  37509. if (!event.isDone) {
  37510. // If event should be done only once, remove it.
  37511. if (event.onlyOnce) {
  37512. this._events.splice(index, 1);
  37513. index--;
  37514. }
  37515. event.isDone = true;
  37516. event.action();
  37517. } // Don't do anything if the event has already be done.
  37518. }
  37519. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  37520. // reset event, the animation is looping
  37521. this._events[index].isDone = false;
  37522. }
  37523. }
  37524. if (!returnValue) {
  37525. this._stopped = true;
  37526. }
  37527. return returnValue;
  37528. };
  37529. Animation.prototype.serialize = function () {
  37530. var serializationObject = {};
  37531. serializationObject.name = this.name;
  37532. serializationObject.property = this.targetProperty;
  37533. serializationObject.framePerSecond = this.framePerSecond;
  37534. serializationObject.dataType = this.dataType;
  37535. serializationObject.loopBehavior = this.loopMode;
  37536. serializationObject.enableBlending = this.enableBlending;
  37537. serializationObject.blendingSpeed = this.blendingSpeed;
  37538. var dataType = this.dataType;
  37539. serializationObject.keys = [];
  37540. var keys = this.getKeys();
  37541. for (var index = 0; index < keys.length; index++) {
  37542. var animationKey = keys[index];
  37543. var key = {};
  37544. key.frame = animationKey.frame;
  37545. switch (dataType) {
  37546. case Animation.ANIMATIONTYPE_FLOAT:
  37547. key.values = [animationKey.value];
  37548. break;
  37549. case Animation.ANIMATIONTYPE_QUATERNION:
  37550. case Animation.ANIMATIONTYPE_MATRIX:
  37551. case Animation.ANIMATIONTYPE_VECTOR3:
  37552. case Animation.ANIMATIONTYPE_COLOR3:
  37553. key.values = animationKey.value.asArray();
  37554. break;
  37555. }
  37556. serializationObject.keys.push(key);
  37557. }
  37558. serializationObject.ranges = [];
  37559. for (var name in this._ranges) {
  37560. var range = {};
  37561. range.name = name;
  37562. range.from = this._ranges[name].from;
  37563. range.to = this._ranges[name].to;
  37564. serializationObject.ranges.push(range);
  37565. }
  37566. return serializationObject;
  37567. };
  37568. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37569. get: function () {
  37570. return Animation._ANIMATIONTYPE_FLOAT;
  37571. },
  37572. enumerable: true,
  37573. configurable: true
  37574. });
  37575. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37576. get: function () {
  37577. return Animation._ANIMATIONTYPE_VECTOR3;
  37578. },
  37579. enumerable: true,
  37580. configurable: true
  37581. });
  37582. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37583. get: function () {
  37584. return Animation._ANIMATIONTYPE_VECTOR2;
  37585. },
  37586. enumerable: true,
  37587. configurable: true
  37588. });
  37589. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37590. get: function () {
  37591. return Animation._ANIMATIONTYPE_SIZE;
  37592. },
  37593. enumerable: true,
  37594. configurable: true
  37595. });
  37596. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37597. get: function () {
  37598. return Animation._ANIMATIONTYPE_QUATERNION;
  37599. },
  37600. enumerable: true,
  37601. configurable: true
  37602. });
  37603. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37604. get: function () {
  37605. return Animation._ANIMATIONTYPE_MATRIX;
  37606. },
  37607. enumerable: true,
  37608. configurable: true
  37609. });
  37610. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37611. get: function () {
  37612. return Animation._ANIMATIONTYPE_COLOR3;
  37613. },
  37614. enumerable: true,
  37615. configurable: true
  37616. });
  37617. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37618. get: function () {
  37619. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37620. },
  37621. enumerable: true,
  37622. configurable: true
  37623. });
  37624. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37625. get: function () {
  37626. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37627. },
  37628. enumerable: true,
  37629. configurable: true
  37630. });
  37631. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37632. get: function () {
  37633. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37634. },
  37635. enumerable: true,
  37636. configurable: true
  37637. });
  37638. Animation.Parse = function (parsedAnimation) {
  37639. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37640. var dataType = parsedAnimation.dataType;
  37641. var keys = [];
  37642. var data;
  37643. var index;
  37644. if (parsedAnimation.enableBlending) {
  37645. animation.enableBlending = parsedAnimation.enableBlending;
  37646. }
  37647. if (parsedAnimation.blendingSpeed) {
  37648. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37649. }
  37650. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37651. var key = parsedAnimation.keys[index];
  37652. switch (dataType) {
  37653. case Animation.ANIMATIONTYPE_FLOAT:
  37654. data = key.values[0];
  37655. break;
  37656. case Animation.ANIMATIONTYPE_QUATERNION:
  37657. data = BABYLON.Quaternion.FromArray(key.values);
  37658. break;
  37659. case Animation.ANIMATIONTYPE_MATRIX:
  37660. data = BABYLON.Matrix.FromArray(key.values);
  37661. break;
  37662. case Animation.ANIMATIONTYPE_COLOR3:
  37663. data = BABYLON.Color3.FromArray(key.values);
  37664. break;
  37665. case Animation.ANIMATIONTYPE_VECTOR3:
  37666. default:
  37667. data = BABYLON.Vector3.FromArray(key.values);
  37668. break;
  37669. }
  37670. keys.push({
  37671. frame: key.frame,
  37672. value: data
  37673. });
  37674. }
  37675. animation.setKeys(keys);
  37676. if (parsedAnimation.ranges) {
  37677. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37678. data = parsedAnimation.ranges[index];
  37679. animation.createRange(data.name, data.from, data.to);
  37680. }
  37681. }
  37682. return animation;
  37683. };
  37684. Animation.AppendSerializedAnimations = function (source, destination) {
  37685. if (source.animations) {
  37686. destination.animations = [];
  37687. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37688. var animation = source.animations[animationIndex];
  37689. destination.animations.push(animation.serialize());
  37690. }
  37691. }
  37692. };
  37693. Animation.AllowMatricesInterpolation = false;
  37694. // Statics
  37695. Animation._ANIMATIONTYPE_FLOAT = 0;
  37696. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37697. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37698. Animation._ANIMATIONTYPE_MATRIX = 3;
  37699. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37700. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37701. Animation._ANIMATIONTYPE_SIZE = 6;
  37702. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37703. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37704. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37705. return Animation;
  37706. }());
  37707. BABYLON.Animation = Animation;
  37708. })(BABYLON || (BABYLON = {}));
  37709. //# sourceMappingURL=babylon.animation.js.map
  37710. var BABYLON;
  37711. (function (BABYLON) {
  37712. var Animatable = (function () {
  37713. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37714. if (fromFrame === void 0) { fromFrame = 0; }
  37715. if (toFrame === void 0) { toFrame = 100; }
  37716. if (loopAnimation === void 0) { loopAnimation = false; }
  37717. if (speedRatio === void 0) { speedRatio = 1.0; }
  37718. this.target = target;
  37719. this.fromFrame = fromFrame;
  37720. this.toFrame = toFrame;
  37721. this.loopAnimation = loopAnimation;
  37722. this.speedRatio = speedRatio;
  37723. this.onAnimationEnd = onAnimationEnd;
  37724. this._localDelayOffset = null;
  37725. this._pausedDelay = null;
  37726. this._animations = new Array();
  37727. this._paused = false;
  37728. this.animationStarted = false;
  37729. if (animations) {
  37730. this.appendAnimations(target, animations);
  37731. }
  37732. this._scene = scene;
  37733. scene._activeAnimatables.push(this);
  37734. }
  37735. // Methods
  37736. Animatable.prototype.getAnimations = function () {
  37737. return this._animations;
  37738. };
  37739. Animatable.prototype.appendAnimations = function (target, animations) {
  37740. for (var index = 0; index < animations.length; index++) {
  37741. var animation = animations[index];
  37742. animation._target = target;
  37743. this._animations.push(animation);
  37744. }
  37745. };
  37746. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37747. var animations = this._animations;
  37748. for (var index = 0; index < animations.length; index++) {
  37749. if (animations[index].targetProperty === property) {
  37750. return animations[index];
  37751. }
  37752. }
  37753. return null;
  37754. };
  37755. Animatable.prototype.reset = function () {
  37756. var animations = this._animations;
  37757. for (var index = 0; index < animations.length; index++) {
  37758. animations[index].reset();
  37759. }
  37760. this._localDelayOffset = null;
  37761. this._pausedDelay = null;
  37762. };
  37763. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37764. var animations = this._animations;
  37765. for (var index = 0; index < animations.length; index++) {
  37766. animations[index].enableBlending = true;
  37767. animations[index].blendingSpeed = blendingSpeed;
  37768. }
  37769. };
  37770. Animatable.prototype.disableBlending = function () {
  37771. var animations = this._animations;
  37772. for (var index = 0; index < animations.length; index++) {
  37773. animations[index].enableBlending = false;
  37774. }
  37775. };
  37776. Animatable.prototype.goToFrame = function (frame) {
  37777. var animations = this._animations;
  37778. if (animations[0]) {
  37779. var fps = animations[0].framePerSecond;
  37780. var currentFrame = animations[0].currentFrame;
  37781. var adjustTime = frame - currentFrame;
  37782. var delay = adjustTime * 1000 / fps;
  37783. this._localDelayOffset -= delay;
  37784. }
  37785. for (var index = 0; index < animations.length; index++) {
  37786. animations[index].goToFrame(frame);
  37787. }
  37788. };
  37789. Animatable.prototype.pause = function () {
  37790. if (this._paused) {
  37791. return;
  37792. }
  37793. this._paused = true;
  37794. };
  37795. Animatable.prototype.restart = function () {
  37796. this._paused = false;
  37797. };
  37798. Animatable.prototype.stop = function (animationName) {
  37799. if (animationName) {
  37800. var idx = this._scene._activeAnimatables.indexOf(this);
  37801. if (idx > -1) {
  37802. var animations = this._animations;
  37803. for (var index = animations.length - 1; index >= 0; index--) {
  37804. if (typeof animationName === "string" && animations[index].name != animationName) {
  37805. continue;
  37806. }
  37807. animations[index].reset();
  37808. animations.splice(index, 1);
  37809. }
  37810. if (animations.length == 0) {
  37811. this._scene._activeAnimatables.splice(idx, 1);
  37812. if (this.onAnimationEnd) {
  37813. this.onAnimationEnd();
  37814. }
  37815. }
  37816. }
  37817. }
  37818. else {
  37819. var index = this._scene._activeAnimatables.indexOf(this);
  37820. if (index > -1) {
  37821. this._scene._activeAnimatables.splice(index, 1);
  37822. var animations = this._animations;
  37823. for (var index = 0; index < animations.length; index++) {
  37824. animations[index].reset();
  37825. }
  37826. if (this.onAnimationEnd) {
  37827. this.onAnimationEnd();
  37828. }
  37829. }
  37830. }
  37831. };
  37832. Animatable.prototype._animate = function (delay) {
  37833. if (this._paused) {
  37834. this.animationStarted = false;
  37835. if (this._pausedDelay === null) {
  37836. this._pausedDelay = delay;
  37837. }
  37838. return true;
  37839. }
  37840. if (this._localDelayOffset === null) {
  37841. this._localDelayOffset = delay;
  37842. }
  37843. else if (this._pausedDelay !== null) {
  37844. this._localDelayOffset += delay - this._pausedDelay;
  37845. this._pausedDelay = null;
  37846. }
  37847. // Animating
  37848. var running = false;
  37849. var animations = this._animations;
  37850. var index;
  37851. for (index = 0; index < animations.length; index++) {
  37852. var animation = animations[index];
  37853. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37854. running = running || isRunning;
  37855. }
  37856. this.animationStarted = running;
  37857. if (!running) {
  37858. // Remove from active animatables
  37859. index = this._scene._activeAnimatables.indexOf(this);
  37860. this._scene._activeAnimatables.splice(index, 1);
  37861. }
  37862. if (!running && this.onAnimationEnd) {
  37863. this.onAnimationEnd();
  37864. this.onAnimationEnd = null;
  37865. }
  37866. return running;
  37867. };
  37868. return Animatable;
  37869. }());
  37870. BABYLON.Animatable = Animatable;
  37871. })(BABYLON || (BABYLON = {}));
  37872. //# sourceMappingURL=babylon.animatable.js.map
  37873. var BABYLON;
  37874. (function (BABYLON) {
  37875. var EasingFunction = (function () {
  37876. function EasingFunction() {
  37877. // Properties
  37878. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37879. }
  37880. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37881. get: function () {
  37882. return EasingFunction._EASINGMODE_EASEIN;
  37883. },
  37884. enumerable: true,
  37885. configurable: true
  37886. });
  37887. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37888. get: function () {
  37889. return EasingFunction._EASINGMODE_EASEOUT;
  37890. },
  37891. enumerable: true,
  37892. configurable: true
  37893. });
  37894. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37895. get: function () {
  37896. return EasingFunction._EASINGMODE_EASEINOUT;
  37897. },
  37898. enumerable: true,
  37899. configurable: true
  37900. });
  37901. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37902. var n = Math.min(Math.max(easingMode, 0), 2);
  37903. this._easingMode = n;
  37904. };
  37905. EasingFunction.prototype.getEasingMode = function () {
  37906. return this._easingMode;
  37907. };
  37908. EasingFunction.prototype.easeInCore = function (gradient) {
  37909. throw new Error('You must implement this method');
  37910. };
  37911. EasingFunction.prototype.ease = function (gradient) {
  37912. switch (this._easingMode) {
  37913. case EasingFunction.EASINGMODE_EASEIN:
  37914. return this.easeInCore(gradient);
  37915. case EasingFunction.EASINGMODE_EASEOUT:
  37916. return (1 - this.easeInCore(1 - gradient));
  37917. }
  37918. if (gradient >= 0.5) {
  37919. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37920. }
  37921. return (this.easeInCore(gradient * 2) * 0.5);
  37922. };
  37923. //Statics
  37924. EasingFunction._EASINGMODE_EASEIN = 0;
  37925. EasingFunction._EASINGMODE_EASEOUT = 1;
  37926. EasingFunction._EASINGMODE_EASEINOUT = 2;
  37927. return EasingFunction;
  37928. }());
  37929. BABYLON.EasingFunction = EasingFunction;
  37930. var CircleEase = (function (_super) {
  37931. __extends(CircleEase, _super);
  37932. function CircleEase() {
  37933. return _super !== null && _super.apply(this, arguments) || this;
  37934. }
  37935. CircleEase.prototype.easeInCore = function (gradient) {
  37936. gradient = Math.max(0, Math.min(1, gradient));
  37937. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  37938. };
  37939. return CircleEase;
  37940. }(EasingFunction));
  37941. BABYLON.CircleEase = CircleEase;
  37942. var BackEase = (function (_super) {
  37943. __extends(BackEase, _super);
  37944. function BackEase(amplitude) {
  37945. if (amplitude === void 0) { amplitude = 1; }
  37946. var _this = _super.call(this) || this;
  37947. _this.amplitude = amplitude;
  37948. return _this;
  37949. }
  37950. BackEase.prototype.easeInCore = function (gradient) {
  37951. var num = Math.max(0, this.amplitude);
  37952. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  37953. };
  37954. return BackEase;
  37955. }(EasingFunction));
  37956. BABYLON.BackEase = BackEase;
  37957. var BounceEase = (function (_super) {
  37958. __extends(BounceEase, _super);
  37959. function BounceEase(bounces, bounciness) {
  37960. if (bounces === void 0) { bounces = 3; }
  37961. if (bounciness === void 0) { bounciness = 2; }
  37962. var _this = _super.call(this) || this;
  37963. _this.bounces = bounces;
  37964. _this.bounciness = bounciness;
  37965. return _this;
  37966. }
  37967. BounceEase.prototype.easeInCore = function (gradient) {
  37968. var y = Math.max(0.0, this.bounces);
  37969. var bounciness = this.bounciness;
  37970. if (bounciness <= 1.0) {
  37971. bounciness = 1.001;
  37972. }
  37973. var num9 = Math.pow(bounciness, y);
  37974. var num5 = 1.0 - bounciness;
  37975. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  37976. var num15 = gradient * num4;
  37977. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  37978. var num3 = Math.floor(num65);
  37979. var num13 = num3 + 1.0;
  37980. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  37981. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  37982. var num7 = (num8 + num12) * 0.5;
  37983. var num6 = gradient - num7;
  37984. var num2 = num7 - num8;
  37985. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  37986. };
  37987. return BounceEase;
  37988. }(EasingFunction));
  37989. BABYLON.BounceEase = BounceEase;
  37990. var CubicEase = (function (_super) {
  37991. __extends(CubicEase, _super);
  37992. function CubicEase() {
  37993. return _super !== null && _super.apply(this, arguments) || this;
  37994. }
  37995. CubicEase.prototype.easeInCore = function (gradient) {
  37996. return (gradient * gradient * gradient);
  37997. };
  37998. return CubicEase;
  37999. }(EasingFunction));
  38000. BABYLON.CubicEase = CubicEase;
  38001. var ElasticEase = (function (_super) {
  38002. __extends(ElasticEase, _super);
  38003. function ElasticEase(oscillations, springiness) {
  38004. if (oscillations === void 0) { oscillations = 3; }
  38005. if (springiness === void 0) { springiness = 3; }
  38006. var _this = _super.call(this) || this;
  38007. _this.oscillations = oscillations;
  38008. _this.springiness = springiness;
  38009. return _this;
  38010. }
  38011. ElasticEase.prototype.easeInCore = function (gradient) {
  38012. var num2;
  38013. var num3 = Math.max(0.0, this.oscillations);
  38014. var num = Math.max(0.0, this.springiness);
  38015. if (num == 0) {
  38016. num2 = gradient;
  38017. }
  38018. else {
  38019. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  38020. }
  38021. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  38022. };
  38023. return ElasticEase;
  38024. }(EasingFunction));
  38025. BABYLON.ElasticEase = ElasticEase;
  38026. var ExponentialEase = (function (_super) {
  38027. __extends(ExponentialEase, _super);
  38028. function ExponentialEase(exponent) {
  38029. if (exponent === void 0) { exponent = 2; }
  38030. var _this = _super.call(this) || this;
  38031. _this.exponent = exponent;
  38032. return _this;
  38033. }
  38034. ExponentialEase.prototype.easeInCore = function (gradient) {
  38035. if (this.exponent <= 0) {
  38036. return gradient;
  38037. }
  38038. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  38039. };
  38040. return ExponentialEase;
  38041. }(EasingFunction));
  38042. BABYLON.ExponentialEase = ExponentialEase;
  38043. var PowerEase = (function (_super) {
  38044. __extends(PowerEase, _super);
  38045. function PowerEase(power) {
  38046. if (power === void 0) { power = 2; }
  38047. var _this = _super.call(this) || this;
  38048. _this.power = power;
  38049. return _this;
  38050. }
  38051. PowerEase.prototype.easeInCore = function (gradient) {
  38052. var y = Math.max(0.0, this.power);
  38053. return Math.pow(gradient, y);
  38054. };
  38055. return PowerEase;
  38056. }(EasingFunction));
  38057. BABYLON.PowerEase = PowerEase;
  38058. var QuadraticEase = (function (_super) {
  38059. __extends(QuadraticEase, _super);
  38060. function QuadraticEase() {
  38061. return _super !== null && _super.apply(this, arguments) || this;
  38062. }
  38063. QuadraticEase.prototype.easeInCore = function (gradient) {
  38064. return (gradient * gradient);
  38065. };
  38066. return QuadraticEase;
  38067. }(EasingFunction));
  38068. BABYLON.QuadraticEase = QuadraticEase;
  38069. var QuarticEase = (function (_super) {
  38070. __extends(QuarticEase, _super);
  38071. function QuarticEase() {
  38072. return _super !== null && _super.apply(this, arguments) || this;
  38073. }
  38074. QuarticEase.prototype.easeInCore = function (gradient) {
  38075. return (gradient * gradient * gradient * gradient);
  38076. };
  38077. return QuarticEase;
  38078. }(EasingFunction));
  38079. BABYLON.QuarticEase = QuarticEase;
  38080. var QuinticEase = (function (_super) {
  38081. __extends(QuinticEase, _super);
  38082. function QuinticEase() {
  38083. return _super !== null && _super.apply(this, arguments) || this;
  38084. }
  38085. QuinticEase.prototype.easeInCore = function (gradient) {
  38086. return (gradient * gradient * gradient * gradient * gradient);
  38087. };
  38088. return QuinticEase;
  38089. }(EasingFunction));
  38090. BABYLON.QuinticEase = QuinticEase;
  38091. var SineEase = (function (_super) {
  38092. __extends(SineEase, _super);
  38093. function SineEase() {
  38094. return _super !== null && _super.apply(this, arguments) || this;
  38095. }
  38096. SineEase.prototype.easeInCore = function (gradient) {
  38097. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  38098. };
  38099. return SineEase;
  38100. }(EasingFunction));
  38101. BABYLON.SineEase = SineEase;
  38102. var BezierCurveEase = (function (_super) {
  38103. __extends(BezierCurveEase, _super);
  38104. function BezierCurveEase(x1, y1, x2, y2) {
  38105. if (x1 === void 0) { x1 = 0; }
  38106. if (y1 === void 0) { y1 = 0; }
  38107. if (x2 === void 0) { x2 = 1; }
  38108. if (y2 === void 0) { y2 = 1; }
  38109. var _this = _super.call(this) || this;
  38110. _this.x1 = x1;
  38111. _this.y1 = y1;
  38112. _this.x2 = x2;
  38113. _this.y2 = y2;
  38114. return _this;
  38115. }
  38116. BezierCurveEase.prototype.easeInCore = function (gradient) {
  38117. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  38118. };
  38119. return BezierCurveEase;
  38120. }(EasingFunction));
  38121. BABYLON.BezierCurveEase = BezierCurveEase;
  38122. })(BABYLON || (BABYLON = {}));
  38123. //# sourceMappingURL=babylon.easing.js.map
  38124. var BABYLON;
  38125. (function (BABYLON) {
  38126. var Condition = (function () {
  38127. function Condition(actionManager) {
  38128. this._actionManager = actionManager;
  38129. }
  38130. Condition.prototype.isValid = function () {
  38131. return true;
  38132. };
  38133. Condition.prototype._getProperty = function (propertyPath) {
  38134. return this._actionManager._getProperty(propertyPath);
  38135. };
  38136. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38137. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38138. };
  38139. Condition.prototype.serialize = function () {
  38140. };
  38141. Condition.prototype._serialize = function (serializedCondition) {
  38142. return {
  38143. type: 2,
  38144. children: [],
  38145. name: serializedCondition.name,
  38146. properties: serializedCondition.properties
  38147. };
  38148. };
  38149. return Condition;
  38150. }());
  38151. BABYLON.Condition = Condition;
  38152. var ValueCondition = (function (_super) {
  38153. __extends(ValueCondition, _super);
  38154. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38155. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38156. var _this = _super.call(this, actionManager) || this;
  38157. _this.propertyPath = propertyPath;
  38158. _this.value = value;
  38159. _this.operator = operator;
  38160. _this._target = target;
  38161. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38162. _this._property = _this._getProperty(_this.propertyPath);
  38163. return _this;
  38164. }
  38165. Object.defineProperty(ValueCondition, "IsEqual", {
  38166. get: function () {
  38167. return ValueCondition._IsEqual;
  38168. },
  38169. enumerable: true,
  38170. configurable: true
  38171. });
  38172. Object.defineProperty(ValueCondition, "IsDifferent", {
  38173. get: function () {
  38174. return ValueCondition._IsDifferent;
  38175. },
  38176. enumerable: true,
  38177. configurable: true
  38178. });
  38179. Object.defineProperty(ValueCondition, "IsGreater", {
  38180. get: function () {
  38181. return ValueCondition._IsGreater;
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. Object.defineProperty(ValueCondition, "IsLesser", {
  38187. get: function () {
  38188. return ValueCondition._IsLesser;
  38189. },
  38190. enumerable: true,
  38191. configurable: true
  38192. });
  38193. // Methods
  38194. ValueCondition.prototype.isValid = function () {
  38195. switch (this.operator) {
  38196. case ValueCondition.IsGreater:
  38197. return this._effectiveTarget[this._property] > this.value;
  38198. case ValueCondition.IsLesser:
  38199. return this._effectiveTarget[this._property] < this.value;
  38200. case ValueCondition.IsEqual:
  38201. case ValueCondition.IsDifferent:
  38202. var check;
  38203. if (this.value.equals) {
  38204. check = this.value.equals(this._effectiveTarget[this._property]);
  38205. }
  38206. else {
  38207. check = this.value === this._effectiveTarget[this._property];
  38208. }
  38209. return this.operator === ValueCondition.IsEqual ? check : !check;
  38210. }
  38211. return false;
  38212. };
  38213. ValueCondition.prototype.serialize = function () {
  38214. return this._serialize({
  38215. name: "ValueCondition",
  38216. properties: [
  38217. BABYLON.Action._GetTargetProperty(this._target),
  38218. { name: "propertyPath", value: this.propertyPath },
  38219. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38220. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38221. ]
  38222. });
  38223. };
  38224. ValueCondition.GetOperatorName = function (operator) {
  38225. switch (operator) {
  38226. case ValueCondition._IsEqual: return "IsEqual";
  38227. case ValueCondition._IsDifferent: return "IsDifferent";
  38228. case ValueCondition._IsGreater: return "IsGreater";
  38229. case ValueCondition._IsLesser: return "IsLesser";
  38230. default: return "";
  38231. }
  38232. };
  38233. // Statics
  38234. ValueCondition._IsEqual = 0;
  38235. ValueCondition._IsDifferent = 1;
  38236. ValueCondition._IsGreater = 2;
  38237. ValueCondition._IsLesser = 3;
  38238. return ValueCondition;
  38239. }(Condition));
  38240. BABYLON.ValueCondition = ValueCondition;
  38241. var PredicateCondition = (function (_super) {
  38242. __extends(PredicateCondition, _super);
  38243. function PredicateCondition(actionManager, predicate) {
  38244. var _this = _super.call(this, actionManager) || this;
  38245. _this.predicate = predicate;
  38246. return _this;
  38247. }
  38248. PredicateCondition.prototype.isValid = function () {
  38249. return this.predicate();
  38250. };
  38251. return PredicateCondition;
  38252. }(Condition));
  38253. BABYLON.PredicateCondition = PredicateCondition;
  38254. var StateCondition = (function (_super) {
  38255. __extends(StateCondition, _super);
  38256. function StateCondition(actionManager, target, value) {
  38257. var _this = _super.call(this, actionManager) || this;
  38258. _this.value = value;
  38259. _this._target = target;
  38260. return _this;
  38261. }
  38262. // Methods
  38263. StateCondition.prototype.isValid = function () {
  38264. return this._target.state === this.value;
  38265. };
  38266. StateCondition.prototype.serialize = function () {
  38267. return this._serialize({
  38268. name: "StateCondition",
  38269. properties: [
  38270. BABYLON.Action._GetTargetProperty(this._target),
  38271. { name: "value", value: this.value }
  38272. ]
  38273. });
  38274. };
  38275. return StateCondition;
  38276. }(Condition));
  38277. BABYLON.StateCondition = StateCondition;
  38278. })(BABYLON || (BABYLON = {}));
  38279. //# sourceMappingURL=babylon.condition.js.map
  38280. var BABYLON;
  38281. (function (BABYLON) {
  38282. var Action = (function () {
  38283. function Action(triggerOptions, condition) {
  38284. this.triggerOptions = triggerOptions;
  38285. if (triggerOptions.parameter) {
  38286. this.trigger = triggerOptions.trigger;
  38287. this._triggerParameter = triggerOptions.parameter;
  38288. }
  38289. else {
  38290. this.trigger = triggerOptions;
  38291. }
  38292. this._nextActiveAction = this;
  38293. this._condition = condition;
  38294. }
  38295. // Methods
  38296. Action.prototype._prepare = function () {
  38297. };
  38298. Action.prototype.getTriggerParameter = function () {
  38299. return this._triggerParameter;
  38300. };
  38301. Action.prototype._executeCurrent = function (evt) {
  38302. if (this._nextActiveAction._condition) {
  38303. var condition = this._nextActiveAction._condition;
  38304. var currentRenderId = this._actionManager.getScene().getRenderId();
  38305. // We cache the current evaluation for the current frame
  38306. if (condition._evaluationId === currentRenderId) {
  38307. if (!condition._currentResult) {
  38308. return;
  38309. }
  38310. }
  38311. else {
  38312. condition._evaluationId = currentRenderId;
  38313. if (!condition.isValid()) {
  38314. condition._currentResult = false;
  38315. return;
  38316. }
  38317. condition._currentResult = true;
  38318. }
  38319. }
  38320. this._nextActiveAction.execute(evt);
  38321. this.skipToNextActiveAction();
  38322. };
  38323. Action.prototype.execute = function (evt) {
  38324. };
  38325. Action.prototype.skipToNextActiveAction = function () {
  38326. if (this._nextActiveAction._child) {
  38327. if (!this._nextActiveAction._child._actionManager) {
  38328. this._nextActiveAction._child._actionManager = this._actionManager;
  38329. }
  38330. this._nextActiveAction = this._nextActiveAction._child;
  38331. }
  38332. else {
  38333. this._nextActiveAction = this;
  38334. }
  38335. };
  38336. Action.prototype.then = function (action) {
  38337. this._child = action;
  38338. action._actionManager = this._actionManager;
  38339. action._prepare();
  38340. return action;
  38341. };
  38342. Action.prototype._getProperty = function (propertyPath) {
  38343. return this._actionManager._getProperty(propertyPath);
  38344. };
  38345. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38346. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38347. };
  38348. Action.prototype.serialize = function (parent) {
  38349. };
  38350. // Called by BABYLON.Action objects in serialize(...). Internal use
  38351. Action.prototype._serialize = function (serializedAction, parent) {
  38352. var serializationObject = {
  38353. type: 1,
  38354. children: [],
  38355. name: serializedAction.name,
  38356. properties: serializedAction.properties || []
  38357. };
  38358. // Serialize child
  38359. if (this._child) {
  38360. this._child.serialize(serializationObject);
  38361. }
  38362. // Check if "this" has a condition
  38363. if (this._condition) {
  38364. var serializedCondition = this._condition.serialize();
  38365. serializedCondition.children.push(serializationObject);
  38366. if (parent) {
  38367. parent.children.push(serializedCondition);
  38368. }
  38369. return serializedCondition;
  38370. }
  38371. if (parent) {
  38372. parent.children.push(serializationObject);
  38373. }
  38374. return serializationObject;
  38375. };
  38376. Action._SerializeValueAsString = function (value) {
  38377. if (typeof value === "number") {
  38378. return value.toString();
  38379. }
  38380. if (typeof value === "boolean") {
  38381. return value ? "true" : "false";
  38382. }
  38383. if (value instanceof BABYLON.Vector2) {
  38384. return value.x + ", " + value.y;
  38385. }
  38386. if (value instanceof BABYLON.Vector3) {
  38387. return value.x + ", " + value.y + ", " + value.z;
  38388. }
  38389. if (value instanceof BABYLON.Color3) {
  38390. return value.r + ", " + value.g + ", " + value.b;
  38391. }
  38392. if (value instanceof BABYLON.Color4) {
  38393. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38394. }
  38395. return value; // string
  38396. };
  38397. Action._GetTargetProperty = function (target) {
  38398. return {
  38399. name: "target",
  38400. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38401. : target instanceof BABYLON.Light ? "LightProperties"
  38402. : target instanceof BABYLON.Camera ? "CameraProperties"
  38403. : "SceneProperties",
  38404. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38405. };
  38406. };
  38407. return Action;
  38408. }());
  38409. BABYLON.Action = Action;
  38410. })(BABYLON || (BABYLON = {}));
  38411. //# sourceMappingURL=babylon.action.js.map
  38412. var BABYLON;
  38413. (function (BABYLON) {
  38414. /**
  38415. * ActionEvent is the event beint sent when an action is triggered.
  38416. */
  38417. var ActionEvent = (function () {
  38418. /**
  38419. * @param source The mesh or sprite that triggered the action.
  38420. * @param pointerX The X mouse cursor position at the time of the event
  38421. * @param pointerY The Y mouse cursor position at the time of the event
  38422. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38423. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38424. */
  38425. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38426. this.source = source;
  38427. this.pointerX = pointerX;
  38428. this.pointerY = pointerY;
  38429. this.meshUnderPointer = meshUnderPointer;
  38430. this.sourceEvent = sourceEvent;
  38431. this.additionalData = additionalData;
  38432. }
  38433. /**
  38434. * Helper function to auto-create an ActionEvent from a source mesh.
  38435. * @param source The source mesh that triggered the event
  38436. * @param evt {Event} The original (browser) event
  38437. */
  38438. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38439. var scene = source.getScene();
  38440. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38441. };
  38442. /**
  38443. * Helper function to auto-create an ActionEvent from a source mesh.
  38444. * @param source The source sprite that triggered the event
  38445. * @param scene Scene associated with the sprite
  38446. * @param evt {Event} The original (browser) event
  38447. */
  38448. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38449. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38450. };
  38451. /**
  38452. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38453. * @param scene the scene where the event occurred
  38454. * @param evt {Event} The original (browser) event
  38455. */
  38456. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38457. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38458. };
  38459. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38460. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38461. };
  38462. return ActionEvent;
  38463. }());
  38464. BABYLON.ActionEvent = ActionEvent;
  38465. /**
  38466. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38467. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38468. */
  38469. var ActionManager = (function () {
  38470. function ActionManager(scene) {
  38471. // Members
  38472. this.actions = new Array();
  38473. this.hoverCursor = '';
  38474. this._scene = scene;
  38475. scene._actionManagers.push(this);
  38476. }
  38477. Object.defineProperty(ActionManager, "NothingTrigger", {
  38478. get: function () {
  38479. return ActionManager._NothingTrigger;
  38480. },
  38481. enumerable: true,
  38482. configurable: true
  38483. });
  38484. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38485. get: function () {
  38486. return ActionManager._OnPickTrigger;
  38487. },
  38488. enumerable: true,
  38489. configurable: true
  38490. });
  38491. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38492. get: function () {
  38493. return ActionManager._OnLeftPickTrigger;
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38499. get: function () {
  38500. return ActionManager._OnRightPickTrigger;
  38501. },
  38502. enumerable: true,
  38503. configurable: true
  38504. });
  38505. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38506. get: function () {
  38507. return ActionManager._OnCenterPickTrigger;
  38508. },
  38509. enumerable: true,
  38510. configurable: true
  38511. });
  38512. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38513. get: function () {
  38514. return ActionManager._OnPickDownTrigger;
  38515. },
  38516. enumerable: true,
  38517. configurable: true
  38518. });
  38519. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38520. get: function () {
  38521. return ActionManager._OnDoublePickTrigger;
  38522. },
  38523. enumerable: true,
  38524. configurable: true
  38525. });
  38526. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38527. get: function () {
  38528. return ActionManager._OnPickUpTrigger;
  38529. },
  38530. enumerable: true,
  38531. configurable: true
  38532. });
  38533. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38534. /// This trigger will only be raised if you also declared a OnPickDown
  38535. get: function () {
  38536. return ActionManager._OnPickOutTrigger;
  38537. },
  38538. enumerable: true,
  38539. configurable: true
  38540. });
  38541. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38542. get: function () {
  38543. return ActionManager._OnLongPressTrigger;
  38544. },
  38545. enumerable: true,
  38546. configurable: true
  38547. });
  38548. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38549. get: function () {
  38550. return ActionManager._OnPointerOverTrigger;
  38551. },
  38552. enumerable: true,
  38553. configurable: true
  38554. });
  38555. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38556. get: function () {
  38557. return ActionManager._OnPointerOutTrigger;
  38558. },
  38559. enumerable: true,
  38560. configurable: true
  38561. });
  38562. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38563. get: function () {
  38564. return ActionManager._OnEveryFrameTrigger;
  38565. },
  38566. enumerable: true,
  38567. configurable: true
  38568. });
  38569. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38570. get: function () {
  38571. return ActionManager._OnIntersectionEnterTrigger;
  38572. },
  38573. enumerable: true,
  38574. configurable: true
  38575. });
  38576. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38577. get: function () {
  38578. return ActionManager._OnIntersectionExitTrigger;
  38579. },
  38580. enumerable: true,
  38581. configurable: true
  38582. });
  38583. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38584. get: function () {
  38585. return ActionManager._OnKeyDownTrigger;
  38586. },
  38587. enumerable: true,
  38588. configurable: true
  38589. });
  38590. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38591. get: function () {
  38592. return ActionManager._OnKeyUpTrigger;
  38593. },
  38594. enumerable: true,
  38595. configurable: true
  38596. });
  38597. // Methods
  38598. ActionManager.prototype.dispose = function () {
  38599. var index = this._scene._actionManagers.indexOf(this);
  38600. for (var i = 0; i < this.actions.length; i++) {
  38601. var action = this.actions[i];
  38602. ActionManager.Triggers[action.trigger]--;
  38603. if (ActionManager.Triggers[action.trigger] === 0) {
  38604. delete ActionManager.Triggers[action.trigger];
  38605. }
  38606. }
  38607. if (index > -1) {
  38608. this._scene._actionManagers.splice(index, 1);
  38609. }
  38610. };
  38611. ActionManager.prototype.getScene = function () {
  38612. return this._scene;
  38613. };
  38614. /**
  38615. * Does this action manager handles actions of any of the given triggers
  38616. * @param {number[]} triggers - the triggers to be tested
  38617. * @return {boolean} whether one (or more) of the triggers is handeled
  38618. */
  38619. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38620. for (var index = 0; index < this.actions.length; index++) {
  38621. var action = this.actions[index];
  38622. if (triggers.indexOf(action.trigger) > -1) {
  38623. return true;
  38624. }
  38625. }
  38626. return false;
  38627. };
  38628. /**
  38629. * Does this action manager handles actions of a given trigger
  38630. * @param {number} trigger - the trigger to be tested
  38631. * @return {boolean} whether the trigger is handeled
  38632. */
  38633. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38634. for (var index = 0; index < this.actions.length; index++) {
  38635. var action = this.actions[index];
  38636. if (action.trigger === trigger) {
  38637. return true;
  38638. }
  38639. }
  38640. return false;
  38641. };
  38642. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38643. /**
  38644. * Does this action manager has pointer triggers
  38645. * @return {boolean} whether or not it has pointer triggers
  38646. */
  38647. get: function () {
  38648. for (var index = 0; index < this.actions.length; index++) {
  38649. var action = this.actions[index];
  38650. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38651. return true;
  38652. }
  38653. }
  38654. return false;
  38655. },
  38656. enumerable: true,
  38657. configurable: true
  38658. });
  38659. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38660. /**
  38661. * Does this action manager has pick triggers
  38662. * @return {boolean} whether or not it has pick triggers
  38663. */
  38664. get: function () {
  38665. for (var index = 0; index < this.actions.length; index++) {
  38666. var action = this.actions[index];
  38667. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38668. return true;
  38669. }
  38670. }
  38671. return false;
  38672. },
  38673. enumerable: true,
  38674. configurable: true
  38675. });
  38676. Object.defineProperty(ActionManager, "HasTriggers", {
  38677. /**
  38678. * Does exist one action manager with at least one trigger
  38679. * @return {boolean} whether or not it exists one action manager with one trigger
  38680. **/
  38681. get: function () {
  38682. for (var t in ActionManager.Triggers) {
  38683. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38684. return true;
  38685. }
  38686. }
  38687. return false;
  38688. },
  38689. enumerable: true,
  38690. configurable: true
  38691. });
  38692. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38693. /**
  38694. * Does exist one action manager with at least one pick trigger
  38695. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38696. **/
  38697. get: function () {
  38698. for (var t in ActionManager.Triggers) {
  38699. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38700. var t_int = parseInt(t);
  38701. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38702. return true;
  38703. }
  38704. }
  38705. }
  38706. return false;
  38707. },
  38708. enumerable: true,
  38709. configurable: true
  38710. });
  38711. /**
  38712. * Does exist one action manager that handles actions of a given trigger
  38713. * @param {number} trigger - the trigger to be tested
  38714. * @return {boolean} whether the trigger is handeled by at least one action manager
  38715. **/
  38716. ActionManager.HasSpecificTrigger = function (trigger) {
  38717. for (var t in ActionManager.Triggers) {
  38718. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38719. var t_int = parseInt(t);
  38720. if (t_int === trigger) {
  38721. return true;
  38722. }
  38723. }
  38724. }
  38725. return false;
  38726. };
  38727. /**
  38728. * Registers an action to this action manager
  38729. * @param {BABYLON.Action} action - the action to be registered
  38730. * @return {BABYLON.Action} the action amended (prepared) after registration
  38731. */
  38732. ActionManager.prototype.registerAction = function (action) {
  38733. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38734. if (this.getScene().actionManager !== this) {
  38735. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38736. return null;
  38737. }
  38738. }
  38739. this.actions.push(action);
  38740. if (ActionManager.Triggers[action.trigger]) {
  38741. ActionManager.Triggers[action.trigger]++;
  38742. }
  38743. else {
  38744. ActionManager.Triggers[action.trigger] = 1;
  38745. }
  38746. action._actionManager = this;
  38747. action._prepare();
  38748. return action;
  38749. };
  38750. /**
  38751. * Process a specific trigger
  38752. * @param {number} trigger - the trigger to process
  38753. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38754. */
  38755. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38756. for (var index = 0; index < this.actions.length; index++) {
  38757. var action = this.actions[index];
  38758. if (action.trigger === trigger) {
  38759. if (trigger === ActionManager.OnKeyUpTrigger
  38760. || trigger === ActionManager.OnKeyDownTrigger) {
  38761. var parameter = action.getTriggerParameter();
  38762. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38763. if (!parameter.toLowerCase) {
  38764. continue;
  38765. }
  38766. var lowerCase = parameter.toLowerCase();
  38767. if (lowerCase !== evt.sourceEvent.key) {
  38768. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38769. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38770. if (actualkey !== lowerCase) {
  38771. continue;
  38772. }
  38773. }
  38774. }
  38775. }
  38776. action._executeCurrent(evt);
  38777. }
  38778. }
  38779. };
  38780. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38781. var properties = propertyPath.split(".");
  38782. for (var index = 0; index < properties.length - 1; index++) {
  38783. target = target[properties[index]];
  38784. }
  38785. return target;
  38786. };
  38787. ActionManager.prototype._getProperty = function (propertyPath) {
  38788. var properties = propertyPath.split(".");
  38789. return properties[properties.length - 1];
  38790. };
  38791. ActionManager.prototype.serialize = function (name) {
  38792. var root = {
  38793. children: [],
  38794. name: name,
  38795. type: 3,
  38796. properties: [] // Empty for root but required
  38797. };
  38798. for (var i = 0; i < this.actions.length; i++) {
  38799. var triggerObject = {
  38800. type: 0,
  38801. children: [],
  38802. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38803. properties: []
  38804. };
  38805. var triggerOptions = this.actions[i].triggerOptions;
  38806. if (triggerOptions && typeof triggerOptions !== "number") {
  38807. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38808. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38809. }
  38810. else {
  38811. var parameter = {};
  38812. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38813. if (triggerOptions.parameter.mesh) {
  38814. parameter._meshId = triggerOptions.parameter.mesh.id;
  38815. }
  38816. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38817. }
  38818. }
  38819. // Serialize child action, recursively
  38820. this.actions[i].serialize(triggerObject);
  38821. // Add serialized trigger
  38822. root.children.push(triggerObject);
  38823. }
  38824. return root;
  38825. };
  38826. ActionManager.Parse = function (parsedActions, object, scene) {
  38827. var actionManager = new BABYLON.ActionManager(scene);
  38828. if (object === null)
  38829. scene.actionManager = actionManager;
  38830. else
  38831. object.actionManager = actionManager;
  38832. // instanciate a new object
  38833. var instanciate = function (name, params) {
  38834. var newInstance = Object.create(BABYLON[name].prototype);
  38835. newInstance.constructor.apply(newInstance, params);
  38836. return newInstance;
  38837. };
  38838. var parseParameter = function (name, value, target, propertyPath) {
  38839. if (propertyPath === null) {
  38840. // String, boolean or float
  38841. var floatValue = parseFloat(value);
  38842. if (value === "true" || value === "false")
  38843. return value === "true";
  38844. else
  38845. return isNaN(floatValue) ? value : floatValue;
  38846. }
  38847. var effectiveTarget = propertyPath.split(".");
  38848. var values = value.split(",");
  38849. // Get effective Target
  38850. for (var i = 0; i < effectiveTarget.length; i++) {
  38851. target = target[effectiveTarget[i]];
  38852. }
  38853. // Return appropriate value with its type
  38854. if (typeof (target) === "boolean")
  38855. return values[0] === "true";
  38856. if (typeof (target) === "string")
  38857. return values[0];
  38858. // Parameters with multiple values such as Vector3 etc.
  38859. var split = new Array();
  38860. for (var i = 0; i < values.length; i++)
  38861. split.push(parseFloat(values[i]));
  38862. if (target instanceof BABYLON.Vector3)
  38863. return BABYLON.Vector3.FromArray(split);
  38864. if (target instanceof BABYLON.Vector4)
  38865. return BABYLON.Vector4.FromArray(split);
  38866. if (target instanceof BABYLON.Color3)
  38867. return BABYLON.Color3.FromArray(split);
  38868. if (target instanceof BABYLON.Color4)
  38869. return BABYLON.Color4.FromArray(split);
  38870. return parseFloat(values[0]);
  38871. };
  38872. // traverse graph per trigger
  38873. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38874. if (combineArray === void 0) { combineArray = null; }
  38875. if (parsedAction.detached)
  38876. return;
  38877. var parameters = new Array();
  38878. var target = null;
  38879. var propertyPath = null;
  38880. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38881. // Parameters
  38882. if (parsedAction.type === 2)
  38883. parameters.push(actionManager);
  38884. else
  38885. parameters.push(trigger);
  38886. if (combine) {
  38887. var actions = new Array();
  38888. for (var j = 0; j < parsedAction.combine.length; j++) {
  38889. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38890. }
  38891. parameters.push(actions);
  38892. }
  38893. else {
  38894. for (var i = 0; i < parsedAction.properties.length; i++) {
  38895. var value = parsedAction.properties[i].value;
  38896. var name = parsedAction.properties[i].name;
  38897. var targetType = parsedAction.properties[i].targetType;
  38898. if (name === "target")
  38899. if (targetType !== null && targetType === "SceneProperties")
  38900. value = target = scene;
  38901. else
  38902. value = target = scene.getNodeByName(value);
  38903. else if (name === "parent")
  38904. value = scene.getNodeByName(value);
  38905. else if (name === "sound")
  38906. value = scene.getSoundByName(value);
  38907. else if (name !== "propertyPath") {
  38908. if (parsedAction.type === 2 && name === "operator")
  38909. value = BABYLON.ValueCondition[value];
  38910. else
  38911. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38912. }
  38913. else {
  38914. propertyPath = value;
  38915. }
  38916. parameters.push(value);
  38917. }
  38918. }
  38919. if (combineArray === null) {
  38920. parameters.push(condition);
  38921. }
  38922. else {
  38923. parameters.push(null);
  38924. }
  38925. // If interpolate value action
  38926. if (parsedAction.name === "InterpolateValueAction") {
  38927. var param = parameters[parameters.length - 2];
  38928. parameters[parameters.length - 1] = param;
  38929. parameters[parameters.length - 2] = condition;
  38930. }
  38931. // Action or condition(s) and not CombineAction
  38932. var newAction = instanciate(parsedAction.name, parameters);
  38933. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38934. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38935. if (action)
  38936. action.then(nothing);
  38937. else
  38938. actionManager.registerAction(nothing);
  38939. action = nothing;
  38940. }
  38941. if (combineArray === null) {
  38942. if (newAction instanceof BABYLON.Condition) {
  38943. condition = newAction;
  38944. newAction = action;
  38945. }
  38946. else {
  38947. condition = null;
  38948. if (action)
  38949. action.then(newAction);
  38950. else
  38951. actionManager.registerAction(newAction);
  38952. }
  38953. }
  38954. else {
  38955. combineArray.push(newAction);
  38956. }
  38957. for (var i = 0; i < parsedAction.children.length; i++)
  38958. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38959. };
  38960. // triggers
  38961. for (var i = 0; i < parsedActions.children.length; i++) {
  38962. var triggerParams;
  38963. var trigger = parsedActions.children[i];
  38964. if (trigger.properties.length > 0) {
  38965. var param = trigger.properties[0].value;
  38966. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38967. if (value._meshId) {
  38968. value.mesh = scene.getMeshByID(value._meshId);
  38969. }
  38970. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38971. }
  38972. else
  38973. triggerParams = BABYLON.ActionManager[trigger.name];
  38974. for (var j = 0; j < trigger.children.length; j++) {
  38975. if (!trigger.detached)
  38976. traverse(trigger.children[j], triggerParams, null, null);
  38977. }
  38978. }
  38979. };
  38980. ActionManager.GetTriggerName = function (trigger) {
  38981. switch (trigger) {
  38982. case 0: return "NothingTrigger";
  38983. case 1: return "OnPickTrigger";
  38984. case 2: return "OnLeftPickTrigger";
  38985. case 3: return "OnRightPickTrigger";
  38986. case 4: return "OnCenterPickTrigger";
  38987. case 5: return "OnPickDownTrigger";
  38988. case 6: return "OnPickUpTrigger";
  38989. case 7: return "OnLongPressTrigger";
  38990. case 8: return "OnPointerOverTrigger";
  38991. case 9: return "OnPointerOutTrigger";
  38992. case 10: return "OnEveryFrameTrigger";
  38993. case 11: return "OnIntersectionEnterTrigger";
  38994. case 12: return "OnIntersectionExitTrigger";
  38995. case 13: return "OnKeyDownTrigger";
  38996. case 14: return "OnKeyUpTrigger";
  38997. case 15: return "OnPickOutTrigger";
  38998. default: return "";
  38999. }
  39000. };
  39001. // Statics
  39002. ActionManager._NothingTrigger = 0;
  39003. ActionManager._OnPickTrigger = 1;
  39004. ActionManager._OnLeftPickTrigger = 2;
  39005. ActionManager._OnRightPickTrigger = 3;
  39006. ActionManager._OnCenterPickTrigger = 4;
  39007. ActionManager._OnPickDownTrigger = 5;
  39008. ActionManager._OnDoublePickTrigger = 6;
  39009. ActionManager._OnPickUpTrigger = 7;
  39010. ActionManager._OnLongPressTrigger = 8;
  39011. ActionManager._OnPointerOverTrigger = 9;
  39012. ActionManager._OnPointerOutTrigger = 10;
  39013. ActionManager._OnEveryFrameTrigger = 11;
  39014. ActionManager._OnIntersectionEnterTrigger = 12;
  39015. ActionManager._OnIntersectionExitTrigger = 13;
  39016. ActionManager._OnKeyDownTrigger = 14;
  39017. ActionManager._OnKeyUpTrigger = 15;
  39018. ActionManager._OnPickOutTrigger = 16;
  39019. ActionManager.Triggers = {};
  39020. return ActionManager;
  39021. }());
  39022. BABYLON.ActionManager = ActionManager;
  39023. })(BABYLON || (BABYLON = {}));
  39024. //# sourceMappingURL=babylon.actionManager.js.map
  39025. var BABYLON;
  39026. (function (BABYLON) {
  39027. var InterpolateValueAction = (function (_super) {
  39028. __extends(InterpolateValueAction, _super);
  39029. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39030. if (duration === void 0) { duration = 1000; }
  39031. var _this = _super.call(this, triggerOptions, condition) || this;
  39032. _this.propertyPath = propertyPath;
  39033. _this.value = value;
  39034. _this.duration = duration;
  39035. _this.stopOtherAnimations = stopOtherAnimations;
  39036. _this.onInterpolationDone = onInterpolationDone;
  39037. _this._target = _this._effectiveTarget = target;
  39038. return _this;
  39039. }
  39040. InterpolateValueAction.prototype._prepare = function () {
  39041. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39042. this._property = this._getProperty(this.propertyPath);
  39043. };
  39044. InterpolateValueAction.prototype.execute = function () {
  39045. var scene = this._actionManager.getScene();
  39046. var keys = [
  39047. {
  39048. frame: 0,
  39049. value: this._effectiveTarget[this._property]
  39050. }, {
  39051. frame: 100,
  39052. value: this.value
  39053. }
  39054. ];
  39055. var dataType;
  39056. if (typeof this.value === "number") {
  39057. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39058. }
  39059. else if (this.value instanceof BABYLON.Color3) {
  39060. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39061. }
  39062. else if (this.value instanceof BABYLON.Vector3) {
  39063. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39064. }
  39065. else if (this.value instanceof BABYLON.Matrix) {
  39066. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39067. }
  39068. else if (this.value instanceof BABYLON.Quaternion) {
  39069. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39070. }
  39071. else {
  39072. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39073. return;
  39074. }
  39075. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39076. animation.setKeys(keys);
  39077. if (this.stopOtherAnimations) {
  39078. scene.stopAnimation(this._effectiveTarget);
  39079. }
  39080. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39081. };
  39082. InterpolateValueAction.prototype.serialize = function (parent) {
  39083. return _super.prototype._serialize.call(this, {
  39084. name: "InterpolateValueAction",
  39085. properties: [
  39086. BABYLON.Action._GetTargetProperty(this._target),
  39087. { name: "propertyPath", value: this.propertyPath },
  39088. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39089. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39090. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39091. ]
  39092. }, parent);
  39093. };
  39094. return InterpolateValueAction;
  39095. }(BABYLON.Action));
  39096. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39097. })(BABYLON || (BABYLON = {}));
  39098. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39099. var BABYLON;
  39100. (function (BABYLON) {
  39101. var SwitchBooleanAction = (function (_super) {
  39102. __extends(SwitchBooleanAction, _super);
  39103. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39104. var _this = _super.call(this, triggerOptions, condition) || this;
  39105. _this.propertyPath = propertyPath;
  39106. _this._target = _this._effectiveTarget = target;
  39107. return _this;
  39108. }
  39109. SwitchBooleanAction.prototype._prepare = function () {
  39110. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39111. this._property = this._getProperty(this.propertyPath);
  39112. };
  39113. SwitchBooleanAction.prototype.execute = function () {
  39114. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39115. };
  39116. SwitchBooleanAction.prototype.serialize = function (parent) {
  39117. return _super.prototype._serialize.call(this, {
  39118. name: "SwitchBooleanAction",
  39119. properties: [
  39120. BABYLON.Action._GetTargetProperty(this._target),
  39121. { name: "propertyPath", value: this.propertyPath }
  39122. ]
  39123. }, parent);
  39124. };
  39125. return SwitchBooleanAction;
  39126. }(BABYLON.Action));
  39127. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39128. var SetStateAction = (function (_super) {
  39129. __extends(SetStateAction, _super);
  39130. function SetStateAction(triggerOptions, target, value, condition) {
  39131. var _this = _super.call(this, triggerOptions, condition) || this;
  39132. _this.value = value;
  39133. _this._target = target;
  39134. return _this;
  39135. }
  39136. SetStateAction.prototype.execute = function () {
  39137. this._target.state = this.value;
  39138. };
  39139. SetStateAction.prototype.serialize = function (parent) {
  39140. return _super.prototype._serialize.call(this, {
  39141. name: "SetStateAction",
  39142. properties: [
  39143. BABYLON.Action._GetTargetProperty(this._target),
  39144. { name: "value", value: this.value }
  39145. ]
  39146. }, parent);
  39147. };
  39148. return SetStateAction;
  39149. }(BABYLON.Action));
  39150. BABYLON.SetStateAction = SetStateAction;
  39151. var SetValueAction = (function (_super) {
  39152. __extends(SetValueAction, _super);
  39153. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39154. var _this = _super.call(this, triggerOptions, condition) || this;
  39155. _this.propertyPath = propertyPath;
  39156. _this.value = value;
  39157. _this._target = _this._effectiveTarget = target;
  39158. return _this;
  39159. }
  39160. SetValueAction.prototype._prepare = function () {
  39161. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39162. this._property = this._getProperty(this.propertyPath);
  39163. };
  39164. SetValueAction.prototype.execute = function () {
  39165. this._effectiveTarget[this._property] = this.value;
  39166. if (this._target.markAsDirty) {
  39167. this._target.markAsDirty(this._property);
  39168. }
  39169. };
  39170. SetValueAction.prototype.serialize = function (parent) {
  39171. return _super.prototype._serialize.call(this, {
  39172. name: "SetValueAction",
  39173. properties: [
  39174. BABYLON.Action._GetTargetProperty(this._target),
  39175. { name: "propertyPath", value: this.propertyPath },
  39176. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39177. ]
  39178. }, parent);
  39179. };
  39180. return SetValueAction;
  39181. }(BABYLON.Action));
  39182. BABYLON.SetValueAction = SetValueAction;
  39183. var IncrementValueAction = (function (_super) {
  39184. __extends(IncrementValueAction, _super);
  39185. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39186. var _this = _super.call(this, triggerOptions, condition) || this;
  39187. _this.propertyPath = propertyPath;
  39188. _this.value = value;
  39189. _this._target = _this._effectiveTarget = target;
  39190. return _this;
  39191. }
  39192. IncrementValueAction.prototype._prepare = function () {
  39193. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39194. this._property = this._getProperty(this.propertyPath);
  39195. if (typeof this._effectiveTarget[this._property] !== "number") {
  39196. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39197. }
  39198. };
  39199. IncrementValueAction.prototype.execute = function () {
  39200. this._effectiveTarget[this._property] += this.value;
  39201. if (this._target.markAsDirty) {
  39202. this._target.markAsDirty(this._property);
  39203. }
  39204. };
  39205. IncrementValueAction.prototype.serialize = function (parent) {
  39206. return _super.prototype._serialize.call(this, {
  39207. name: "IncrementValueAction",
  39208. properties: [
  39209. BABYLON.Action._GetTargetProperty(this._target),
  39210. { name: "propertyPath", value: this.propertyPath },
  39211. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39212. ]
  39213. }, parent);
  39214. };
  39215. return IncrementValueAction;
  39216. }(BABYLON.Action));
  39217. BABYLON.IncrementValueAction = IncrementValueAction;
  39218. var PlayAnimationAction = (function (_super) {
  39219. __extends(PlayAnimationAction, _super);
  39220. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39221. var _this = _super.call(this, triggerOptions, condition) || this;
  39222. _this.from = from;
  39223. _this.to = to;
  39224. _this.loop = loop;
  39225. _this._target = target;
  39226. return _this;
  39227. }
  39228. PlayAnimationAction.prototype._prepare = function () {
  39229. };
  39230. PlayAnimationAction.prototype.execute = function () {
  39231. var scene = this._actionManager.getScene();
  39232. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39233. };
  39234. PlayAnimationAction.prototype.serialize = function (parent) {
  39235. return _super.prototype._serialize.call(this, {
  39236. name: "PlayAnimationAction",
  39237. properties: [
  39238. BABYLON.Action._GetTargetProperty(this._target),
  39239. { name: "from", value: String(this.from) },
  39240. { name: "to", value: String(this.to) },
  39241. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39242. ]
  39243. }, parent);
  39244. };
  39245. return PlayAnimationAction;
  39246. }(BABYLON.Action));
  39247. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39248. var StopAnimationAction = (function (_super) {
  39249. __extends(StopAnimationAction, _super);
  39250. function StopAnimationAction(triggerOptions, target, condition) {
  39251. var _this = _super.call(this, triggerOptions, condition) || this;
  39252. _this._target = target;
  39253. return _this;
  39254. }
  39255. StopAnimationAction.prototype._prepare = function () {
  39256. };
  39257. StopAnimationAction.prototype.execute = function () {
  39258. var scene = this._actionManager.getScene();
  39259. scene.stopAnimation(this._target);
  39260. };
  39261. StopAnimationAction.prototype.serialize = function (parent) {
  39262. return _super.prototype._serialize.call(this, {
  39263. name: "StopAnimationAction",
  39264. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39265. }, parent);
  39266. };
  39267. return StopAnimationAction;
  39268. }(BABYLON.Action));
  39269. BABYLON.StopAnimationAction = StopAnimationAction;
  39270. var DoNothingAction = (function (_super) {
  39271. __extends(DoNothingAction, _super);
  39272. function DoNothingAction(triggerOptions, condition) {
  39273. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39274. return _super.call(this, triggerOptions, condition) || this;
  39275. }
  39276. DoNothingAction.prototype.execute = function () {
  39277. };
  39278. DoNothingAction.prototype.serialize = function (parent) {
  39279. return _super.prototype._serialize.call(this, {
  39280. name: "DoNothingAction",
  39281. properties: []
  39282. }, parent);
  39283. };
  39284. return DoNothingAction;
  39285. }(BABYLON.Action));
  39286. BABYLON.DoNothingAction = DoNothingAction;
  39287. var CombineAction = (function (_super) {
  39288. __extends(CombineAction, _super);
  39289. function CombineAction(triggerOptions, children, condition) {
  39290. var _this = _super.call(this, triggerOptions, condition) || this;
  39291. _this.children = children;
  39292. return _this;
  39293. }
  39294. CombineAction.prototype._prepare = function () {
  39295. for (var index = 0; index < this.children.length; index++) {
  39296. this.children[index]._actionManager = this._actionManager;
  39297. this.children[index]._prepare();
  39298. }
  39299. };
  39300. CombineAction.prototype.execute = function (evt) {
  39301. for (var index = 0; index < this.children.length; index++) {
  39302. this.children[index].execute(evt);
  39303. }
  39304. };
  39305. CombineAction.prototype.serialize = function (parent) {
  39306. var serializationObject = _super.prototype._serialize.call(this, {
  39307. name: "CombineAction",
  39308. properties: [],
  39309. combine: []
  39310. }, parent);
  39311. for (var i = 0; i < this.children.length; i++) {
  39312. serializationObject.combine.push(this.children[i].serialize(null));
  39313. }
  39314. return serializationObject;
  39315. };
  39316. return CombineAction;
  39317. }(BABYLON.Action));
  39318. BABYLON.CombineAction = CombineAction;
  39319. var ExecuteCodeAction = (function (_super) {
  39320. __extends(ExecuteCodeAction, _super);
  39321. function ExecuteCodeAction(triggerOptions, func, condition) {
  39322. var _this = _super.call(this, triggerOptions, condition) || this;
  39323. _this.func = func;
  39324. return _this;
  39325. }
  39326. ExecuteCodeAction.prototype.execute = function (evt) {
  39327. this.func(evt);
  39328. };
  39329. return ExecuteCodeAction;
  39330. }(BABYLON.Action));
  39331. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39332. var SetParentAction = (function (_super) {
  39333. __extends(SetParentAction, _super);
  39334. function SetParentAction(triggerOptions, target, parent, condition) {
  39335. var _this = _super.call(this, triggerOptions, condition) || this;
  39336. _this._target = target;
  39337. _this._parent = parent;
  39338. return _this;
  39339. }
  39340. SetParentAction.prototype._prepare = function () {
  39341. };
  39342. SetParentAction.prototype.execute = function () {
  39343. if (this._target.parent === this._parent) {
  39344. return;
  39345. }
  39346. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39347. invertParentWorldMatrix.invert();
  39348. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39349. this._target.parent = this._parent;
  39350. };
  39351. SetParentAction.prototype.serialize = function (parent) {
  39352. return _super.prototype._serialize.call(this, {
  39353. name: "SetParentAction",
  39354. properties: [
  39355. BABYLON.Action._GetTargetProperty(this._target),
  39356. BABYLON.Action._GetTargetProperty(this._parent),
  39357. ]
  39358. }, parent);
  39359. };
  39360. return SetParentAction;
  39361. }(BABYLON.Action));
  39362. BABYLON.SetParentAction = SetParentAction;
  39363. var PlaySoundAction = (function (_super) {
  39364. __extends(PlaySoundAction, _super);
  39365. function PlaySoundAction(triggerOptions, sound, condition) {
  39366. var _this = _super.call(this, triggerOptions, condition) || this;
  39367. _this._sound = sound;
  39368. return _this;
  39369. }
  39370. PlaySoundAction.prototype._prepare = function () {
  39371. };
  39372. PlaySoundAction.prototype.execute = function () {
  39373. if (this._sound !== undefined)
  39374. this._sound.play();
  39375. };
  39376. PlaySoundAction.prototype.serialize = function (parent) {
  39377. return _super.prototype._serialize.call(this, {
  39378. name: "PlaySoundAction",
  39379. properties: [{ name: "sound", value: this._sound.name }]
  39380. }, parent);
  39381. };
  39382. return PlaySoundAction;
  39383. }(BABYLON.Action));
  39384. BABYLON.PlaySoundAction = PlaySoundAction;
  39385. var StopSoundAction = (function (_super) {
  39386. __extends(StopSoundAction, _super);
  39387. function StopSoundAction(triggerOptions, sound, condition) {
  39388. var _this = _super.call(this, triggerOptions, condition) || this;
  39389. _this._sound = sound;
  39390. return _this;
  39391. }
  39392. StopSoundAction.prototype._prepare = function () {
  39393. };
  39394. StopSoundAction.prototype.execute = function () {
  39395. if (this._sound !== undefined)
  39396. this._sound.stop();
  39397. };
  39398. StopSoundAction.prototype.serialize = function (parent) {
  39399. return _super.prototype._serialize.call(this, {
  39400. name: "StopSoundAction",
  39401. properties: [{ name: "sound", value: this._sound.name }]
  39402. }, parent);
  39403. };
  39404. return StopSoundAction;
  39405. }(BABYLON.Action));
  39406. BABYLON.StopSoundAction = StopSoundAction;
  39407. })(BABYLON || (BABYLON = {}));
  39408. //# sourceMappingURL=babylon.directActions.js.map
  39409. var BABYLON;
  39410. (function (BABYLON) {
  39411. var SpriteManager = (function () {
  39412. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39413. if (epsilon === void 0) { epsilon = 0.01; }
  39414. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39415. this.name = name;
  39416. this.sprites = new Array();
  39417. this.renderingGroupId = 0;
  39418. this.layerMask = 0x0FFFFFFF;
  39419. this.fogEnabled = true;
  39420. this.isPickable = false;
  39421. /**
  39422. * An event triggered when the manager is disposed.
  39423. * @type {BABYLON.Observable}
  39424. */
  39425. this.onDisposeObservable = new BABYLON.Observable();
  39426. this._vertexBuffers = {};
  39427. this._capacity = capacity;
  39428. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39429. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39430. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39431. if (cellSize.width && cellSize.height) {
  39432. this.cellWidth = cellSize.width;
  39433. this.cellHeight = cellSize.height;
  39434. }
  39435. else if (cellSize !== undefined) {
  39436. this.cellWidth = cellSize;
  39437. this.cellHeight = cellSize;
  39438. }
  39439. else {
  39440. return;
  39441. }
  39442. this._epsilon = epsilon;
  39443. this._scene = scene;
  39444. this._scene.spriteManagers.push(this);
  39445. var indices = [];
  39446. var index = 0;
  39447. for (var count = 0; count < capacity; count++) {
  39448. indices.push(index);
  39449. indices.push(index + 1);
  39450. indices.push(index + 2);
  39451. indices.push(index);
  39452. indices.push(index + 2);
  39453. indices.push(index + 3);
  39454. index += 4;
  39455. }
  39456. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39457. // VBO
  39458. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39459. this._vertexData = new Float32Array(capacity * 16 * 4);
  39460. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39461. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39462. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39463. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39464. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39465. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39466. this._vertexBuffers["options"] = options;
  39467. this._vertexBuffers["cellInfo"] = cellInfo;
  39468. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39469. // Effects
  39470. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39471. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39472. }
  39473. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39474. set: function (callback) {
  39475. if (this._onDisposeObserver) {
  39476. this.onDisposeObservable.remove(this._onDisposeObserver);
  39477. }
  39478. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39479. },
  39480. enumerable: true,
  39481. configurable: true
  39482. });
  39483. Object.defineProperty(SpriteManager.prototype, "texture", {
  39484. get: function () {
  39485. return this._spriteTexture;
  39486. },
  39487. set: function (value) {
  39488. this._spriteTexture = value;
  39489. },
  39490. enumerable: true,
  39491. configurable: true
  39492. });
  39493. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39494. var arrayOffset = index * 16;
  39495. if (offsetX === 0)
  39496. offsetX = this._epsilon;
  39497. else if (offsetX === 1)
  39498. offsetX = 1 - this._epsilon;
  39499. if (offsetY === 0)
  39500. offsetY = this._epsilon;
  39501. else if (offsetY === 1)
  39502. offsetY = 1 - this._epsilon;
  39503. this._vertexData[arrayOffset] = sprite.position.x;
  39504. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39505. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39506. this._vertexData[arrayOffset + 3] = sprite.angle;
  39507. this._vertexData[arrayOffset + 4] = sprite.width;
  39508. this._vertexData[arrayOffset + 5] = sprite.height;
  39509. this._vertexData[arrayOffset + 6] = offsetX;
  39510. this._vertexData[arrayOffset + 7] = offsetY;
  39511. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39512. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39513. var offset = (sprite.cellIndex / rowSize) >> 0;
  39514. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39515. this._vertexData[arrayOffset + 11] = offset;
  39516. // Color
  39517. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39518. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39519. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39520. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39521. };
  39522. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39523. var count = Math.min(this._capacity, this.sprites.length);
  39524. var min = BABYLON.Vector3.Zero();
  39525. var max = BABYLON.Vector3.Zero();
  39526. var distance = Number.MAX_VALUE;
  39527. var currentSprite;
  39528. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39529. var cameraView = camera.getViewMatrix();
  39530. for (var index = 0; index < count; index++) {
  39531. var sprite = this.sprites[index];
  39532. if (!sprite) {
  39533. continue;
  39534. }
  39535. if (predicate) {
  39536. if (!predicate(sprite)) {
  39537. continue;
  39538. }
  39539. }
  39540. else if (!sprite.isPickable) {
  39541. continue;
  39542. }
  39543. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39544. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39545. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39546. if (ray.intersectsBoxMinMax(min, max)) {
  39547. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39548. if (distance > currentDistance) {
  39549. distance = currentDistance;
  39550. currentSprite = sprite;
  39551. if (fastCheck) {
  39552. break;
  39553. }
  39554. }
  39555. }
  39556. }
  39557. if (currentSprite) {
  39558. var result = new BABYLON.PickingInfo();
  39559. result.hit = true;
  39560. result.pickedSprite = currentSprite;
  39561. result.distance = distance;
  39562. return result;
  39563. }
  39564. return null;
  39565. };
  39566. SpriteManager.prototype.render = function () {
  39567. // Check
  39568. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39569. return;
  39570. var engine = this._scene.getEngine();
  39571. var baseSize = this._spriteTexture.getBaseSize();
  39572. // Sprites
  39573. var deltaTime = engine.getDeltaTime();
  39574. var max = Math.min(this._capacity, this.sprites.length);
  39575. var rowSize = baseSize.width / this.cellWidth;
  39576. var offset = 0;
  39577. for (var index = 0; index < max; index++) {
  39578. var sprite = this.sprites[index];
  39579. if (!sprite) {
  39580. continue;
  39581. }
  39582. sprite._animate(deltaTime);
  39583. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39584. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39585. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39586. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39587. }
  39588. this._buffer.update(this._vertexData);
  39589. // Render
  39590. var effect = this._effectBase;
  39591. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39592. effect = this._effectFog;
  39593. }
  39594. engine.enableEffect(effect);
  39595. var viewMatrix = this._scene.getViewMatrix();
  39596. effect.setTexture("diffuseSampler", this._spriteTexture);
  39597. effect.setMatrix("view", viewMatrix);
  39598. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39599. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39600. // Fog
  39601. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39602. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39603. effect.setColor3("vFogColor", this._scene.fogColor);
  39604. }
  39605. // VBOs
  39606. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39607. // Draw order
  39608. engine.setDepthFunctionToLessOrEqual();
  39609. effect.setBool("alphaTest", true);
  39610. engine.setColorWrite(false);
  39611. engine.draw(true, 0, max * 6);
  39612. engine.setColorWrite(true);
  39613. effect.setBool("alphaTest", false);
  39614. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39615. engine.draw(true, 0, max * 6);
  39616. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39617. };
  39618. SpriteManager.prototype.dispose = function () {
  39619. if (this._buffer) {
  39620. this._buffer.dispose();
  39621. this._buffer = null;
  39622. }
  39623. if (this._indexBuffer) {
  39624. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39625. this._indexBuffer = null;
  39626. }
  39627. if (this._spriteTexture) {
  39628. this._spriteTexture.dispose();
  39629. this._spriteTexture = null;
  39630. }
  39631. // Remove from scene
  39632. var index = this._scene.spriteManagers.indexOf(this);
  39633. this._scene.spriteManagers.splice(index, 1);
  39634. // Callback
  39635. this.onDisposeObservable.notifyObservers(this);
  39636. this.onDisposeObservable.clear();
  39637. };
  39638. return SpriteManager;
  39639. }());
  39640. BABYLON.SpriteManager = SpriteManager;
  39641. })(BABYLON || (BABYLON = {}));
  39642. //# sourceMappingURL=babylon.spriteManager.js.map
  39643. var BABYLON;
  39644. (function (BABYLON) {
  39645. var Sprite = (function () {
  39646. function Sprite(name, manager) {
  39647. this.name = name;
  39648. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39649. this.width = 1.0;
  39650. this.height = 1.0;
  39651. this.angle = 0;
  39652. this.cellIndex = 0;
  39653. this.invertU = 0;
  39654. this.invertV = 0;
  39655. this.animations = new Array();
  39656. this.isPickable = false;
  39657. this._animationStarted = false;
  39658. this._loopAnimation = false;
  39659. this._fromIndex = 0;
  39660. this._toIndex = 0;
  39661. this._delay = 0;
  39662. this._direction = 1;
  39663. this._frameCount = 0;
  39664. this._time = 0;
  39665. this._manager = manager;
  39666. this._manager.sprites.push(this);
  39667. this.position = BABYLON.Vector3.Zero();
  39668. }
  39669. Object.defineProperty(Sprite.prototype, "size", {
  39670. get: function () {
  39671. return this.width;
  39672. },
  39673. set: function (value) {
  39674. this.width = value;
  39675. this.height = value;
  39676. },
  39677. enumerable: true,
  39678. configurable: true
  39679. });
  39680. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39681. this._fromIndex = from;
  39682. this._toIndex = to;
  39683. this._loopAnimation = loop;
  39684. this._delay = delay;
  39685. this._animationStarted = true;
  39686. this._direction = from < to ? 1 : -1;
  39687. this.cellIndex = from;
  39688. this._time = 0;
  39689. this._onAnimationEnd = onAnimationEnd;
  39690. };
  39691. Sprite.prototype.stopAnimation = function () {
  39692. this._animationStarted = false;
  39693. };
  39694. Sprite.prototype._animate = function (deltaTime) {
  39695. if (!this._animationStarted)
  39696. return;
  39697. this._time += deltaTime;
  39698. if (this._time > this._delay) {
  39699. this._time = this._time % this._delay;
  39700. this.cellIndex += this._direction;
  39701. if (this.cellIndex > this._toIndex) {
  39702. if (this._loopAnimation) {
  39703. this.cellIndex = this._fromIndex;
  39704. }
  39705. else {
  39706. this.cellIndex = this._toIndex;
  39707. this._animationStarted = false;
  39708. if (this._onAnimationEnd) {
  39709. this._onAnimationEnd();
  39710. }
  39711. if (this.disposeWhenFinishedAnimating) {
  39712. this.dispose();
  39713. }
  39714. }
  39715. }
  39716. }
  39717. };
  39718. Sprite.prototype.dispose = function () {
  39719. for (var i = 0; i < this._manager.sprites.length; i++) {
  39720. if (this._manager.sprites[i] == this) {
  39721. this._manager.sprites.splice(i, 1);
  39722. }
  39723. }
  39724. };
  39725. return Sprite;
  39726. }());
  39727. BABYLON.Sprite = Sprite;
  39728. })(BABYLON || (BABYLON = {}));
  39729. //# sourceMappingURL=babylon.sprite.js.map
  39730. var BABYLON;
  39731. (function (BABYLON) {
  39732. var IntersectionInfo = (function () {
  39733. function IntersectionInfo(bu, bv, distance) {
  39734. this.bu = bu;
  39735. this.bv = bv;
  39736. this.distance = distance;
  39737. this.faceId = 0;
  39738. this.subMeshId = 0;
  39739. }
  39740. return IntersectionInfo;
  39741. }());
  39742. BABYLON.IntersectionInfo = IntersectionInfo;
  39743. var PickingInfo = (function () {
  39744. function PickingInfo() {
  39745. this.hit = false;
  39746. this.distance = 0;
  39747. this.pickedPoint = null;
  39748. this.pickedMesh = null;
  39749. this.bu = 0;
  39750. this.bv = 0;
  39751. this.faceId = -1;
  39752. this.subMeshId = 0;
  39753. this.pickedSprite = null;
  39754. }
  39755. // Methods
  39756. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39757. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39758. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39759. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39760. return null;
  39761. }
  39762. var indices = this.pickedMesh.getIndices();
  39763. var result;
  39764. if (useVerticesNormals) {
  39765. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39766. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39767. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39768. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39769. normal0 = normal0.scale(this.bu);
  39770. normal1 = normal1.scale(this.bv);
  39771. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39772. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39773. }
  39774. else {
  39775. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39776. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39777. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39778. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39779. var p1p2 = vertex1.subtract(vertex2);
  39780. var p3p2 = vertex3.subtract(vertex2);
  39781. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39782. }
  39783. if (useWorldCoordinates) {
  39784. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39785. }
  39786. return BABYLON.Vector3.Normalize(result);
  39787. };
  39788. PickingInfo.prototype.getTextureCoordinates = function () {
  39789. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39790. return null;
  39791. }
  39792. var indices = this.pickedMesh.getIndices();
  39793. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39794. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39795. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39796. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39797. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39798. uv1 = uv1.scale(this.bu);
  39799. uv2 = uv2.scale(this.bv);
  39800. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39801. };
  39802. return PickingInfo;
  39803. }());
  39804. BABYLON.PickingInfo = PickingInfo;
  39805. })(BABYLON || (BABYLON = {}));
  39806. //# sourceMappingURL=babylon.pickingInfo.js.map
  39807. var BABYLON;
  39808. (function (BABYLON) {
  39809. var Ray = (function () {
  39810. function Ray(origin, direction, length) {
  39811. if (length === void 0) { length = Number.MAX_VALUE; }
  39812. this.origin = origin;
  39813. this.direction = direction;
  39814. this.length = length;
  39815. }
  39816. // Methods
  39817. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39818. var d = 0.0;
  39819. var maxValue = Number.MAX_VALUE;
  39820. var inv;
  39821. var min;
  39822. var max;
  39823. var temp;
  39824. if (Math.abs(this.direction.x) < 0.0000001) {
  39825. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39826. return false;
  39827. }
  39828. }
  39829. else {
  39830. inv = 1.0 / this.direction.x;
  39831. min = (minimum.x - this.origin.x) * inv;
  39832. max = (maximum.x - this.origin.x) * inv;
  39833. if (max === -Infinity) {
  39834. max = Infinity;
  39835. }
  39836. if (min > max) {
  39837. temp = min;
  39838. min = max;
  39839. max = temp;
  39840. }
  39841. d = Math.max(min, d);
  39842. maxValue = Math.min(max, maxValue);
  39843. if (d > maxValue) {
  39844. return false;
  39845. }
  39846. }
  39847. if (Math.abs(this.direction.y) < 0.0000001) {
  39848. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39849. return false;
  39850. }
  39851. }
  39852. else {
  39853. inv = 1.0 / this.direction.y;
  39854. min = (minimum.y - this.origin.y) * inv;
  39855. max = (maximum.y - this.origin.y) * inv;
  39856. if (max === -Infinity) {
  39857. max = Infinity;
  39858. }
  39859. if (min > max) {
  39860. temp = min;
  39861. min = max;
  39862. max = temp;
  39863. }
  39864. d = Math.max(min, d);
  39865. maxValue = Math.min(max, maxValue);
  39866. if (d > maxValue) {
  39867. return false;
  39868. }
  39869. }
  39870. if (Math.abs(this.direction.z) < 0.0000001) {
  39871. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39872. return false;
  39873. }
  39874. }
  39875. else {
  39876. inv = 1.0 / this.direction.z;
  39877. min = (minimum.z - this.origin.z) * inv;
  39878. max = (maximum.z - this.origin.z) * inv;
  39879. if (max === -Infinity) {
  39880. max = Infinity;
  39881. }
  39882. if (min > max) {
  39883. temp = min;
  39884. min = max;
  39885. max = temp;
  39886. }
  39887. d = Math.max(min, d);
  39888. maxValue = Math.min(max, maxValue);
  39889. if (d > maxValue) {
  39890. return false;
  39891. }
  39892. }
  39893. return true;
  39894. };
  39895. Ray.prototype.intersectsBox = function (box) {
  39896. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39897. };
  39898. Ray.prototype.intersectsSphere = function (sphere) {
  39899. var x = sphere.center.x - this.origin.x;
  39900. var y = sphere.center.y - this.origin.y;
  39901. var z = sphere.center.z - this.origin.z;
  39902. var pyth = (x * x) + (y * y) + (z * z);
  39903. var rr = sphere.radius * sphere.radius;
  39904. if (pyth <= rr) {
  39905. return true;
  39906. }
  39907. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39908. if (dot < 0.0) {
  39909. return false;
  39910. }
  39911. var temp = pyth - (dot * dot);
  39912. return temp <= rr;
  39913. };
  39914. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39915. if (!this._edge1) {
  39916. this._edge1 = BABYLON.Vector3.Zero();
  39917. this._edge2 = BABYLON.Vector3.Zero();
  39918. this._pvec = BABYLON.Vector3.Zero();
  39919. this._tvec = BABYLON.Vector3.Zero();
  39920. this._qvec = BABYLON.Vector3.Zero();
  39921. }
  39922. vertex1.subtractToRef(vertex0, this._edge1);
  39923. vertex2.subtractToRef(vertex0, this._edge2);
  39924. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39925. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39926. if (det === 0) {
  39927. return null;
  39928. }
  39929. var invdet = 1 / det;
  39930. this.origin.subtractToRef(vertex0, this._tvec);
  39931. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  39932. if (bu < 0 || bu > 1.0) {
  39933. return null;
  39934. }
  39935. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  39936. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  39937. if (bv < 0 || bu + bv > 1.0) {
  39938. return null;
  39939. }
  39940. //check if the distance is longer than the predefined length.
  39941. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  39942. if (distance > this.length) {
  39943. return null;
  39944. }
  39945. return new BABYLON.IntersectionInfo(bu, bv, distance);
  39946. };
  39947. Ray.prototype.intersectsPlane = function (plane) {
  39948. var distance;
  39949. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  39950. if (Math.abs(result1) < 9.99999997475243E-07) {
  39951. return null;
  39952. }
  39953. else {
  39954. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  39955. distance = (-plane.d - result2) / result1;
  39956. if (distance < 0.0) {
  39957. if (distance < -9.99999997475243E-07) {
  39958. return null;
  39959. }
  39960. else {
  39961. return 0;
  39962. }
  39963. }
  39964. return distance;
  39965. }
  39966. };
  39967. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  39968. var tm = BABYLON.Tmp.Matrix[0];
  39969. mesh.getWorldMatrix().invertToRef(tm);
  39970. if (this._tmpRay) {
  39971. Ray.TransformToRef(this, tm, this._tmpRay);
  39972. }
  39973. else {
  39974. this._tmpRay = Ray.Transform(this, tm);
  39975. }
  39976. return mesh.intersects(this._tmpRay, fastCheck);
  39977. };
  39978. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  39979. if (results) {
  39980. results.length = 0;
  39981. }
  39982. else {
  39983. results = [];
  39984. }
  39985. for (var i = 0; i < meshes.length; i++) {
  39986. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  39987. if (pickInfo.hit) {
  39988. results.push(pickInfo);
  39989. }
  39990. }
  39991. results.sort(this._comparePickingInfo);
  39992. return results;
  39993. };
  39994. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  39995. if (pickingInfoA.distance < pickingInfoB.distance) {
  39996. return -1;
  39997. }
  39998. else if (pickingInfoA.distance > pickingInfoB.distance) {
  39999. return 1;
  40000. }
  40001. else {
  40002. return 0;
  40003. }
  40004. };
  40005. /**
  40006. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  40007. * @param sega the first point of the segment to test the intersection against
  40008. * @param segb the second point of the segment to test the intersection against
  40009. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  40010. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  40011. */
  40012. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  40013. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  40014. var u = segb.subtract(sega);
  40015. var v = rsegb.subtract(this.origin);
  40016. var w = sega.subtract(this.origin);
  40017. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  40018. var b = BABYLON.Vector3.Dot(u, v);
  40019. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  40020. var d = BABYLON.Vector3.Dot(u, w);
  40021. var e = BABYLON.Vector3.Dot(v, w);
  40022. var D = a * c - b * b; // always >= 0
  40023. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  40024. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  40025. // compute the line parameters of the two closest points
  40026. if (D < Ray.smallnum) {
  40027. sN = 0.0; // force using point P0 on segment S1
  40028. sD = 1.0; // to prevent possible division by 0.0 later
  40029. tN = e;
  40030. tD = c;
  40031. }
  40032. else {
  40033. sN = (b * e - c * d);
  40034. tN = (a * e - b * d);
  40035. if (sN < 0.0) {
  40036. sN = 0.0;
  40037. tN = e;
  40038. tD = c;
  40039. }
  40040. else if (sN > sD) {
  40041. sN = sD;
  40042. tN = e + b;
  40043. tD = c;
  40044. }
  40045. }
  40046. if (tN < 0.0) {
  40047. tN = 0.0;
  40048. // recompute sc for this edge
  40049. if (-d < 0.0) {
  40050. sN = 0.0;
  40051. }
  40052. else if (-d > a)
  40053. sN = sD;
  40054. else {
  40055. sN = -d;
  40056. sD = a;
  40057. }
  40058. }
  40059. else if (tN > tD) {
  40060. tN = tD;
  40061. // recompute sc for this edge
  40062. if ((-d + b) < 0.0) {
  40063. sN = 0;
  40064. }
  40065. else if ((-d + b) > a) {
  40066. sN = sD;
  40067. }
  40068. else {
  40069. sN = (-d + b);
  40070. sD = a;
  40071. }
  40072. }
  40073. // finally do the division to get sc and tc
  40074. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  40075. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  40076. // get the difference of the two closest points
  40077. var qtc = v.multiplyByFloats(tc, tc, tc);
  40078. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  40079. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  40080. if (isIntersected) {
  40081. return qtc.length();
  40082. }
  40083. return -1;
  40084. };
  40085. // Statics
  40086. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  40087. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  40088. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  40089. var direction = end.subtract(start);
  40090. direction.normalize();
  40091. return new Ray(start, direction);
  40092. };
  40093. /**
  40094. * 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
  40095. * transformed to the given world matrix.
  40096. * @param origin The origin point
  40097. * @param end The end point
  40098. * @param world a matrix to transform the ray to. Default is the identity matrix.
  40099. */
  40100. Ray.CreateNewFromTo = function (origin, end, world) {
  40101. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  40102. var direction = end.subtract(origin);
  40103. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  40104. direction.normalize();
  40105. return Ray.Transform(new Ray(origin, direction, length), world);
  40106. };
  40107. Ray.Transform = function (ray, matrix) {
  40108. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  40109. Ray.TransformToRef(ray, matrix, result);
  40110. return result;
  40111. };
  40112. Ray.TransformToRef = function (ray, matrix, result) {
  40113. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  40114. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  40115. result.length = ray.length;
  40116. var dir = result.direction;
  40117. var len = dir.length();
  40118. if (!(len === 0 || len === 1)) {
  40119. var num = 1.0 / len;
  40120. dir.x *= num;
  40121. dir.y *= num;
  40122. dir.z *= num;
  40123. result.length *= len;
  40124. }
  40125. };
  40126. Ray.smallnum = 0.00000001;
  40127. Ray.rayl = 10e8;
  40128. return Ray;
  40129. }());
  40130. BABYLON.Ray = Ray;
  40131. })(BABYLON || (BABYLON = {}));
  40132. //# sourceMappingURL=babylon.ray.js.map
  40133. var BABYLON;
  40134. (function (BABYLON) {
  40135. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40136. if (boxMin.x > sphereCenter.x + sphereRadius)
  40137. return false;
  40138. if (sphereCenter.x - sphereRadius > boxMax.x)
  40139. return false;
  40140. if (boxMin.y > sphereCenter.y + sphereRadius)
  40141. return false;
  40142. if (sphereCenter.y - sphereRadius > boxMax.y)
  40143. return false;
  40144. if (boxMin.z > sphereCenter.z + sphereRadius)
  40145. return false;
  40146. if (sphereCenter.z - sphereRadius > boxMax.z)
  40147. return false;
  40148. return true;
  40149. };
  40150. var getLowestRoot = (function () {
  40151. var result = { root: 0, found: false };
  40152. return function (a, b, c, maxR) {
  40153. result.root = 0;
  40154. result.found = false;
  40155. var determinant = b * b - 4.0 * a * c;
  40156. if (determinant < 0)
  40157. return result;
  40158. var sqrtD = Math.sqrt(determinant);
  40159. var r1 = (-b - sqrtD) / (2.0 * a);
  40160. var r2 = (-b + sqrtD) / (2.0 * a);
  40161. if (r1 > r2) {
  40162. var temp = r2;
  40163. r2 = r1;
  40164. r1 = temp;
  40165. }
  40166. if (r1 > 0 && r1 < maxR) {
  40167. result.root = r1;
  40168. result.found = true;
  40169. return result;
  40170. }
  40171. if (r2 > 0 && r2 < maxR) {
  40172. result.root = r2;
  40173. result.found = true;
  40174. return result;
  40175. }
  40176. return result;
  40177. };
  40178. })();
  40179. var Collider = (function () {
  40180. function Collider() {
  40181. this.radius = BABYLON.Vector3.One();
  40182. this.retry = 0;
  40183. this.basePointWorld = BABYLON.Vector3.Zero();
  40184. this.velocityWorld = BABYLON.Vector3.Zero();
  40185. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40186. this._collisionPoint = BABYLON.Vector3.Zero();
  40187. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40188. this._tempVector = BABYLON.Vector3.Zero();
  40189. this._tempVector2 = BABYLON.Vector3.Zero();
  40190. this._tempVector3 = BABYLON.Vector3.Zero();
  40191. this._tempVector4 = BABYLON.Vector3.Zero();
  40192. this._edge = BABYLON.Vector3.Zero();
  40193. this._baseToVertex = BABYLON.Vector3.Zero();
  40194. this._destinationPoint = BABYLON.Vector3.Zero();
  40195. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40196. this._displacementVector = BABYLON.Vector3.Zero();
  40197. this._collisionMask = -1;
  40198. }
  40199. Object.defineProperty(Collider.prototype, "collisionMask", {
  40200. get: function () {
  40201. return this._collisionMask;
  40202. },
  40203. set: function (mask) {
  40204. this._collisionMask = !isNaN(mask) ? mask : -1;
  40205. },
  40206. enumerable: true,
  40207. configurable: true
  40208. });
  40209. // Methods
  40210. Collider.prototype._initialize = function (source, dir, e) {
  40211. this.velocity = dir;
  40212. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40213. this.basePoint = source;
  40214. source.multiplyToRef(this.radius, this.basePointWorld);
  40215. dir.multiplyToRef(this.radius, this.velocityWorld);
  40216. this.velocityWorldLength = this.velocityWorld.length();
  40217. this.epsilon = e;
  40218. this.collisionFound = false;
  40219. };
  40220. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40221. pa.subtractToRef(point, this._tempVector);
  40222. pb.subtractToRef(point, this._tempVector2);
  40223. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40224. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40225. if (d < 0)
  40226. return false;
  40227. pc.subtractToRef(point, this._tempVector3);
  40228. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40229. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40230. if (d < 0)
  40231. return false;
  40232. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40233. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40234. return d >= 0;
  40235. };
  40236. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40237. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40238. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40239. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40240. return false;
  40241. }
  40242. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40243. return false;
  40244. return true;
  40245. };
  40246. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40247. var t0;
  40248. var embeddedInPlane = false;
  40249. //defensive programming, actually not needed.
  40250. if (!trianglePlaneArray) {
  40251. trianglePlaneArray = [];
  40252. }
  40253. if (!trianglePlaneArray[faceIndex]) {
  40254. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40255. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40256. }
  40257. var trianglePlane = trianglePlaneArray[faceIndex];
  40258. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40259. return;
  40260. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40261. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40262. if (normalDotVelocity == 0) {
  40263. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40264. return;
  40265. embeddedInPlane = true;
  40266. t0 = 0;
  40267. }
  40268. else {
  40269. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40270. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40271. if (t0 > t1) {
  40272. var temp = t1;
  40273. t1 = t0;
  40274. t0 = temp;
  40275. }
  40276. if (t0 > 1.0 || t1 < 0.0)
  40277. return;
  40278. if (t0 < 0)
  40279. t0 = 0;
  40280. if (t0 > 1.0)
  40281. t0 = 1.0;
  40282. }
  40283. this._collisionPoint.copyFromFloats(0, 0, 0);
  40284. var found = false;
  40285. var t = 1.0;
  40286. if (!embeddedInPlane) {
  40287. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40288. this.velocity.scaleToRef(t0, this._tempVector);
  40289. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40290. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40291. found = true;
  40292. t = t0;
  40293. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40294. }
  40295. }
  40296. if (!found) {
  40297. var velocitySquaredLength = this.velocity.lengthSquared();
  40298. var a = velocitySquaredLength;
  40299. this.basePoint.subtractToRef(p1, this._tempVector);
  40300. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40301. var c = this._tempVector.lengthSquared() - 1.0;
  40302. var lowestRoot = getLowestRoot(a, b, c, t);
  40303. if (lowestRoot.found) {
  40304. t = lowestRoot.root;
  40305. found = true;
  40306. this._collisionPoint.copyFrom(p1);
  40307. }
  40308. this.basePoint.subtractToRef(p2, this._tempVector);
  40309. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40310. c = this._tempVector.lengthSquared() - 1.0;
  40311. lowestRoot = getLowestRoot(a, b, c, t);
  40312. if (lowestRoot.found) {
  40313. t = lowestRoot.root;
  40314. found = true;
  40315. this._collisionPoint.copyFrom(p2);
  40316. }
  40317. this.basePoint.subtractToRef(p3, this._tempVector);
  40318. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40319. c = this._tempVector.lengthSquared() - 1.0;
  40320. lowestRoot = getLowestRoot(a, b, c, t);
  40321. if (lowestRoot.found) {
  40322. t = lowestRoot.root;
  40323. found = true;
  40324. this._collisionPoint.copyFrom(p3);
  40325. }
  40326. p2.subtractToRef(p1, this._edge);
  40327. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40328. var edgeSquaredLength = this._edge.lengthSquared();
  40329. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40330. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40331. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40332. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40333. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40334. lowestRoot = getLowestRoot(a, b, c, t);
  40335. if (lowestRoot.found) {
  40336. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40337. if (f >= 0.0 && f <= 1.0) {
  40338. t = lowestRoot.root;
  40339. found = true;
  40340. this._edge.scaleInPlace(f);
  40341. p1.addToRef(this._edge, this._collisionPoint);
  40342. }
  40343. }
  40344. p3.subtractToRef(p2, this._edge);
  40345. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40346. edgeSquaredLength = this._edge.lengthSquared();
  40347. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40348. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40349. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40350. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40351. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40352. lowestRoot = getLowestRoot(a, b, c, t);
  40353. if (lowestRoot.found) {
  40354. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40355. if (f >= 0.0 && f <= 1.0) {
  40356. t = lowestRoot.root;
  40357. found = true;
  40358. this._edge.scaleInPlace(f);
  40359. p2.addToRef(this._edge, this._collisionPoint);
  40360. }
  40361. }
  40362. p1.subtractToRef(p3, this._edge);
  40363. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40364. edgeSquaredLength = this._edge.lengthSquared();
  40365. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40366. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40367. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40368. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40369. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40370. lowestRoot = getLowestRoot(a, b, c, t);
  40371. if (lowestRoot.found) {
  40372. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40373. if (f >= 0.0 && f <= 1.0) {
  40374. t = lowestRoot.root;
  40375. found = true;
  40376. this._edge.scaleInPlace(f);
  40377. p3.addToRef(this._edge, this._collisionPoint);
  40378. }
  40379. }
  40380. }
  40381. if (found) {
  40382. var distToCollision = t * this.velocity.length();
  40383. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40384. if (!this.intersectionPoint) {
  40385. this.intersectionPoint = this._collisionPoint.clone();
  40386. }
  40387. else {
  40388. this.intersectionPoint.copyFrom(this._collisionPoint);
  40389. }
  40390. this.nearestDistance = distToCollision;
  40391. this.collisionFound = true;
  40392. }
  40393. }
  40394. };
  40395. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40396. for (var i = indexStart; i < indexEnd; i += 3) {
  40397. var p1 = pts[indices[i] - decal];
  40398. var p2 = pts[indices[i + 1] - decal];
  40399. var p3 = pts[indices[i + 2] - decal];
  40400. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40401. }
  40402. };
  40403. Collider.prototype._getResponse = function (pos, vel) {
  40404. pos.addToRef(vel, this._destinationPoint);
  40405. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40406. this.basePoint.addToRef(vel, pos);
  40407. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40408. this._slidePlaneNormal.normalize();
  40409. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40410. pos.addInPlace(this._displacementVector);
  40411. this.intersectionPoint.addInPlace(this._displacementVector);
  40412. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40413. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40414. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40415. };
  40416. return Collider;
  40417. }());
  40418. BABYLON.Collider = Collider;
  40419. })(BABYLON || (BABYLON = {}));
  40420. //# sourceMappingURL=babylon.collider.js.map
  40421. var BABYLON;
  40422. (function (BABYLON) {
  40423. //WebWorker code will be inserted to this variable.
  40424. BABYLON.CollisionWorker = "";
  40425. var WorkerTaskType;
  40426. (function (WorkerTaskType) {
  40427. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40428. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40429. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40430. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40431. var WorkerReplyType;
  40432. (function (WorkerReplyType) {
  40433. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40434. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40435. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40436. var CollisionCoordinatorWorker = (function () {
  40437. function CollisionCoordinatorWorker() {
  40438. var _this = this;
  40439. this._scaledPosition = BABYLON.Vector3.Zero();
  40440. this._scaledVelocity = BABYLON.Vector3.Zero();
  40441. this.onMeshUpdated = function (mesh) {
  40442. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40443. };
  40444. this.onGeometryUpdated = function (geometry) {
  40445. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40446. };
  40447. this._afterRender = function () {
  40448. if (!_this._init)
  40449. return;
  40450. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40451. return;
  40452. }
  40453. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40454. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40455. if (_this._runningUpdated > 4) {
  40456. return;
  40457. }
  40458. ++_this._runningUpdated;
  40459. var payload = {
  40460. updatedMeshes: _this._addUpdateMeshesList,
  40461. updatedGeometries: _this._addUpdateGeometriesList,
  40462. removedGeometries: _this._toRemoveGeometryArray,
  40463. removedMeshes: _this._toRemoveMeshesArray
  40464. };
  40465. var message = {
  40466. payload: payload,
  40467. taskType: WorkerTaskType.UPDATE
  40468. };
  40469. var serializable = [];
  40470. for (var id in payload.updatedGeometries) {
  40471. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40472. //prepare transferables
  40473. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40474. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40475. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40476. }
  40477. }
  40478. _this._worker.postMessage(message, serializable);
  40479. _this._addUpdateMeshesList = {};
  40480. _this._addUpdateGeometriesList = {};
  40481. _this._toRemoveGeometryArray = [];
  40482. _this._toRemoveMeshesArray = [];
  40483. };
  40484. this._onMessageFromWorker = function (e) {
  40485. var returnData = e.data;
  40486. if (returnData.error != WorkerReplyType.SUCCESS) {
  40487. //TODO what errors can be returned from the worker?
  40488. BABYLON.Tools.Warn("error returned from worker!");
  40489. return;
  40490. }
  40491. switch (returnData.taskType) {
  40492. case WorkerTaskType.INIT:
  40493. _this._init = true;
  40494. //Update the worked with ALL of the scene's current state
  40495. _this._scene.meshes.forEach(function (mesh) {
  40496. _this.onMeshAdded(mesh);
  40497. });
  40498. _this._scene.getGeometries().forEach(function (geometry) {
  40499. _this.onGeometryAdded(geometry);
  40500. });
  40501. break;
  40502. case WorkerTaskType.UPDATE:
  40503. _this._runningUpdated--;
  40504. break;
  40505. case WorkerTaskType.COLLIDE:
  40506. _this._runningCollisionTask = false;
  40507. var returnPayload = returnData.payload;
  40508. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40509. return;
  40510. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40511. //cleanup
  40512. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40513. break;
  40514. }
  40515. };
  40516. this._collisionsCallbackArray = [];
  40517. this._init = false;
  40518. this._runningUpdated = 0;
  40519. this._runningCollisionTask = false;
  40520. this._addUpdateMeshesList = {};
  40521. this._addUpdateGeometriesList = {};
  40522. this._toRemoveGeometryArray = [];
  40523. this._toRemoveMeshesArray = [];
  40524. }
  40525. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40526. if (!this._init)
  40527. return;
  40528. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40529. return;
  40530. position.divideToRef(collider.radius, this._scaledPosition);
  40531. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40532. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40533. var payload = {
  40534. collider: {
  40535. position: this._scaledPosition.asArray(),
  40536. velocity: this._scaledVelocity.asArray(),
  40537. radius: collider.radius.asArray()
  40538. },
  40539. collisionId: collisionIndex,
  40540. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40541. maximumRetry: maximumRetry
  40542. };
  40543. var message = {
  40544. payload: payload,
  40545. taskType: WorkerTaskType.COLLIDE
  40546. };
  40547. this._worker.postMessage(message);
  40548. };
  40549. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40550. this._scene = scene;
  40551. this._scene.registerAfterRender(this._afterRender);
  40552. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40553. this._worker = new Worker(workerUrl);
  40554. this._worker.onmessage = this._onMessageFromWorker;
  40555. var message = {
  40556. payload: {},
  40557. taskType: WorkerTaskType.INIT
  40558. };
  40559. this._worker.postMessage(message);
  40560. };
  40561. CollisionCoordinatorWorker.prototype.destroy = function () {
  40562. this._scene.unregisterAfterRender(this._afterRender);
  40563. this._worker.terminate();
  40564. };
  40565. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40566. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40567. this.onMeshUpdated(mesh);
  40568. };
  40569. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40570. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40571. };
  40572. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40573. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40574. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40575. this.onGeometryUpdated(geometry);
  40576. };
  40577. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40578. this._toRemoveGeometryArray.push(geometry.id);
  40579. };
  40580. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40581. var submeshes = [];
  40582. if (mesh.subMeshes) {
  40583. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40584. return {
  40585. position: idx,
  40586. verticesStart: sm.verticesStart,
  40587. verticesCount: sm.verticesCount,
  40588. indexStart: sm.indexStart,
  40589. indexCount: sm.indexCount,
  40590. hasMaterial: !!sm.getMaterial(),
  40591. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40592. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40593. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40594. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40595. };
  40596. });
  40597. }
  40598. var geometryId = null;
  40599. if (mesh instanceof BABYLON.Mesh) {
  40600. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40601. }
  40602. else if (mesh instanceof BABYLON.InstancedMesh) {
  40603. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40604. }
  40605. return {
  40606. uniqueId: mesh.uniqueId,
  40607. id: mesh.id,
  40608. name: mesh.name,
  40609. geometryId: geometryId,
  40610. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40611. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40612. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40613. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40614. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40615. subMeshes: submeshes,
  40616. checkCollisions: mesh.checkCollisions
  40617. };
  40618. };
  40619. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40620. return {
  40621. id: geometry.id,
  40622. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40623. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40624. indices: new Uint32Array(geometry.getIndices() || []),
  40625. };
  40626. };
  40627. return CollisionCoordinatorWorker;
  40628. }());
  40629. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40630. var CollisionCoordinatorLegacy = (function () {
  40631. function CollisionCoordinatorLegacy() {
  40632. this._scaledPosition = BABYLON.Vector3.Zero();
  40633. this._scaledVelocity = BABYLON.Vector3.Zero();
  40634. this._finalPosition = BABYLON.Vector3.Zero();
  40635. }
  40636. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40637. position.divideToRef(collider.radius, this._scaledPosition);
  40638. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40639. collider.collidedMesh = null;
  40640. collider.retry = 0;
  40641. collider.initialVelocity = this._scaledVelocity;
  40642. collider.initialPosition = this._scaledPosition;
  40643. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40644. this._finalPosition.multiplyInPlace(collider.radius);
  40645. //run the callback
  40646. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40647. };
  40648. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40649. this._scene = scene;
  40650. };
  40651. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40652. //Legacy need no destruction method.
  40653. };
  40654. //No update in legacy mode
  40655. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40656. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40657. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40658. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40659. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40660. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40661. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40662. if (excludedMesh === void 0) { excludedMesh = null; }
  40663. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40664. if (collider.retry >= maximumRetry) {
  40665. finalPosition.copyFrom(position);
  40666. return;
  40667. }
  40668. // Check if this is a mesh else camera or -1
  40669. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40670. collider._initialize(position, velocity, closeDistance);
  40671. // Check all meshes
  40672. for (var index = 0; index < this._scene.meshes.length; index++) {
  40673. var mesh = this._scene.meshes[index];
  40674. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40675. mesh._checkCollision(collider);
  40676. }
  40677. }
  40678. if (!collider.collisionFound) {
  40679. position.addToRef(velocity, finalPosition);
  40680. return;
  40681. }
  40682. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40683. collider._getResponse(position, velocity);
  40684. }
  40685. if (velocity.length() <= closeDistance) {
  40686. finalPosition.copyFrom(position);
  40687. return;
  40688. }
  40689. collider.retry++;
  40690. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40691. };
  40692. return CollisionCoordinatorLegacy;
  40693. }());
  40694. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40695. })(BABYLON || (BABYLON = {}));
  40696. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40697. var BABYLON;
  40698. (function (BABYLON) {
  40699. var Particle = (function () {
  40700. function Particle() {
  40701. this.position = BABYLON.Vector3.Zero();
  40702. this.direction = BABYLON.Vector3.Zero();
  40703. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40704. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40705. this.lifeTime = 1.0;
  40706. this.age = 0;
  40707. this.size = 0;
  40708. this.angle = 0;
  40709. this.angularSpeed = 0;
  40710. }
  40711. Particle.prototype.copyTo = function (other) {
  40712. other.position.copyFrom(this.position);
  40713. other.direction.copyFrom(this.direction);
  40714. other.color.copyFrom(this.color);
  40715. other.colorStep.copyFrom(this.colorStep);
  40716. other.lifeTime = this.lifeTime;
  40717. other.age = this.age;
  40718. other.size = this.size;
  40719. other.angle = this.angle;
  40720. other.angularSpeed = this.angularSpeed;
  40721. };
  40722. return Particle;
  40723. }());
  40724. BABYLON.Particle = Particle;
  40725. })(BABYLON || (BABYLON = {}));
  40726. //# sourceMappingURL=babylon.particle.js.map
  40727. var BABYLON;
  40728. (function (BABYLON) {
  40729. var randomNumber = function (min, max) {
  40730. if (min === max) {
  40731. return (min);
  40732. }
  40733. var random = Math.random();
  40734. return ((random * (max - min)) + min);
  40735. };
  40736. var ParticleSystem = (function () {
  40737. function ParticleSystem(name, capacity, scene, customEffect) {
  40738. var _this = this;
  40739. this.name = name;
  40740. // Members
  40741. this.animations = [];
  40742. this.renderingGroupId = 0;
  40743. this.emitter = null;
  40744. this.emitRate = 10;
  40745. this.manualEmitCount = -1;
  40746. this.updateSpeed = 0.01;
  40747. this.targetStopDuration = 0;
  40748. this.disposeOnStop = false;
  40749. this.minEmitPower = 1;
  40750. this.maxEmitPower = 1;
  40751. this.minLifeTime = 1;
  40752. this.maxLifeTime = 1;
  40753. this.minSize = 1;
  40754. this.maxSize = 1;
  40755. this.minAngularSpeed = 0;
  40756. this.maxAngularSpeed = 0;
  40757. this.layerMask = 0x0FFFFFFF;
  40758. this.customShader = null;
  40759. this.preventAutoStart = false;
  40760. /**
  40761. * An event triggered when the system is disposed.
  40762. * @type {BABYLON.Observable}
  40763. */
  40764. this.onDisposeObservable = new BABYLON.Observable();
  40765. this.onAnimationEnd = null;
  40766. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40767. this.forceDepthWrite = false;
  40768. this.gravity = BABYLON.Vector3.Zero();
  40769. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40770. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40771. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40772. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40773. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40774. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40775. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40776. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40777. this.particles = new Array();
  40778. this._stockParticles = new Array();
  40779. this._newPartsExcess = 0;
  40780. this._vertexBuffers = {};
  40781. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40782. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40783. this._scaledDirection = BABYLON.Vector3.Zero();
  40784. this._scaledGravity = BABYLON.Vector3.Zero();
  40785. this._currentRenderId = -1;
  40786. this._started = false;
  40787. this._stopped = false;
  40788. this._actualFrame = 0;
  40789. this.id = name;
  40790. this._capacity = capacity;
  40791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40792. this._customEffect = customEffect;
  40793. scene.particleSystems.push(this);
  40794. this._createIndexBuffer();
  40795. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40796. this._vertexData = new Float32Array(capacity * 11 * 4);
  40797. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  40798. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40799. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40800. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40802. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40803. this._vertexBuffers["options"] = options;
  40804. // Default behaviors
  40805. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40806. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40807. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40808. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40809. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40810. };
  40811. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40812. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40813. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40814. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40815. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40816. };
  40817. this.updateFunction = function (particles) {
  40818. for (var index = 0; index < particles.length; index++) {
  40819. var particle = particles[index];
  40820. particle.age += _this._scaledUpdateSpeed;
  40821. if (particle.age >= particle.lifeTime) {
  40822. _this.recycleParticle(particle);
  40823. index--;
  40824. continue;
  40825. }
  40826. else {
  40827. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40828. particle.color.addInPlace(_this._scaledColorStep);
  40829. if (particle.color.a < 0)
  40830. particle.color.a = 0;
  40831. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40832. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40833. particle.position.addInPlace(_this._scaledDirection);
  40834. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40835. particle.direction.addInPlace(_this._scaledGravity);
  40836. }
  40837. }
  40838. };
  40839. }
  40840. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40841. set: function (callback) {
  40842. if (this._onDisposeObserver) {
  40843. this.onDisposeObservable.remove(this._onDisposeObserver);
  40844. }
  40845. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40846. },
  40847. enumerable: true,
  40848. configurable: true
  40849. });
  40850. ParticleSystem.prototype._createIndexBuffer = function () {
  40851. var indices = [];
  40852. var index = 0;
  40853. for (var count = 0; count < this._capacity; count++) {
  40854. indices.push(index);
  40855. indices.push(index + 1);
  40856. indices.push(index + 2);
  40857. indices.push(index);
  40858. indices.push(index + 2);
  40859. indices.push(index + 3);
  40860. index += 4;
  40861. }
  40862. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40863. };
  40864. ParticleSystem.prototype.recycleParticle = function (particle) {
  40865. var lastParticle = this.particles.pop();
  40866. if (lastParticle !== particle) {
  40867. lastParticle.copyTo(particle);
  40868. this._stockParticles.push(lastParticle);
  40869. }
  40870. };
  40871. ParticleSystem.prototype.getCapacity = function () {
  40872. return this._capacity;
  40873. };
  40874. ParticleSystem.prototype.isAlive = function () {
  40875. return this._alive;
  40876. };
  40877. ParticleSystem.prototype.isStarted = function () {
  40878. return this._started;
  40879. };
  40880. ParticleSystem.prototype.start = function () {
  40881. this._started = true;
  40882. this._stopped = false;
  40883. this._actualFrame = 0;
  40884. };
  40885. ParticleSystem.prototype.stop = function () {
  40886. this._stopped = true;
  40887. };
  40888. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  40889. var offset = index * 11;
  40890. this._vertexData[offset] = particle.position.x;
  40891. this._vertexData[offset + 1] = particle.position.y;
  40892. this._vertexData[offset + 2] = particle.position.z;
  40893. this._vertexData[offset + 3] = particle.color.r;
  40894. this._vertexData[offset + 4] = particle.color.g;
  40895. this._vertexData[offset + 5] = particle.color.b;
  40896. this._vertexData[offset + 6] = particle.color.a;
  40897. this._vertexData[offset + 7] = particle.angle;
  40898. this._vertexData[offset + 8] = particle.size;
  40899. this._vertexData[offset + 9] = offsetX;
  40900. this._vertexData[offset + 10] = offsetY;
  40901. };
  40902. ParticleSystem.prototype._update = function (newParticles) {
  40903. // Update current
  40904. this._alive = this.particles.length > 0;
  40905. this.updateFunction(this.particles);
  40906. // Add new ones
  40907. var worldMatrix;
  40908. if (this.emitter.position) {
  40909. var emitterMesh = this.emitter;
  40910. worldMatrix = emitterMesh.getWorldMatrix();
  40911. }
  40912. else {
  40913. var emitterPosition = this.emitter;
  40914. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  40915. }
  40916. var particle;
  40917. for (var index = 0; index < newParticles; index++) {
  40918. if (this.particles.length === this._capacity) {
  40919. break;
  40920. }
  40921. if (this._stockParticles.length !== 0) {
  40922. particle = this._stockParticles.pop();
  40923. particle.age = 0;
  40924. }
  40925. else {
  40926. particle = new BABYLON.Particle();
  40927. }
  40928. this.particles.push(particle);
  40929. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  40930. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  40931. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  40932. particle.size = randomNumber(this.minSize, this.maxSize);
  40933. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  40934. this.startPositionFunction(worldMatrix, particle.position, particle);
  40935. var step = randomNumber(0, 1.0);
  40936. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  40937. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  40938. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  40939. }
  40940. };
  40941. ParticleSystem.prototype._getEffect = function () {
  40942. if (this._customEffect) {
  40943. return this._customEffect;
  40944. }
  40945. ;
  40946. var defines = [];
  40947. if (this._scene.clipPlane) {
  40948. defines.push("#define CLIPPLANE");
  40949. }
  40950. // Effect
  40951. var join = defines.join("\n");
  40952. if (this._cachedDefines !== join) {
  40953. this._cachedDefines = join;
  40954. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  40955. }
  40956. return this._effect;
  40957. };
  40958. ParticleSystem.prototype.animate = function () {
  40959. if (!this._started)
  40960. return;
  40961. var effect = this._getEffect();
  40962. // Check
  40963. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  40964. return;
  40965. if (this._currentRenderId === this._scene.getRenderId()) {
  40966. return;
  40967. }
  40968. this._currentRenderId = this._scene.getRenderId();
  40969. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  40970. // determine the number of particles we need to create
  40971. var newParticles;
  40972. if (this.manualEmitCount > -1) {
  40973. newParticles = this.manualEmitCount;
  40974. this._newPartsExcess = 0;
  40975. this.manualEmitCount = 0;
  40976. }
  40977. else {
  40978. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  40979. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  40980. }
  40981. if (this._newPartsExcess > 1.0) {
  40982. newParticles += this._newPartsExcess >> 0;
  40983. this._newPartsExcess -= this._newPartsExcess >> 0;
  40984. }
  40985. this._alive = false;
  40986. if (!this._stopped) {
  40987. this._actualFrame += this._scaledUpdateSpeed;
  40988. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  40989. this.stop();
  40990. }
  40991. else {
  40992. newParticles = 0;
  40993. }
  40994. this._update(newParticles);
  40995. // Stopped?
  40996. if (this._stopped) {
  40997. if (!this._alive) {
  40998. this._started = false;
  40999. if (this.onAnimationEnd) {
  41000. this.onAnimationEnd();
  41001. }
  41002. if (this.disposeOnStop) {
  41003. this._scene._toBeDisposed.push(this);
  41004. }
  41005. }
  41006. }
  41007. // Update VBO
  41008. var offset = 0;
  41009. for (var index = 0; index < this.particles.length; index++) {
  41010. var particle = this.particles[index];
  41011. this._appendParticleVertex(offset++, particle, 0, 0);
  41012. this._appendParticleVertex(offset++, particle, 1, 0);
  41013. this._appendParticleVertex(offset++, particle, 1, 1);
  41014. this._appendParticleVertex(offset++, particle, 0, 1);
  41015. }
  41016. this._vertexBuffer.update(this._vertexData);
  41017. };
  41018. ParticleSystem.prototype.rebuild = function () {
  41019. this._createIndexBuffer();
  41020. this._vertexBuffer._rebuild();
  41021. };
  41022. ParticleSystem.prototype.render = function () {
  41023. var effect = this._getEffect();
  41024. // Check
  41025. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  41026. return 0;
  41027. var engine = this._scene.getEngine();
  41028. // Render
  41029. engine.enableEffect(effect);
  41030. engine.setState(false);
  41031. var viewMatrix = this._scene.getViewMatrix();
  41032. effect.setTexture("diffuseSampler", this.particleTexture);
  41033. effect.setMatrix("view", viewMatrix);
  41034. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41035. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  41036. if (this._scene.clipPlane) {
  41037. var clipPlane = this._scene.clipPlane;
  41038. var invView = viewMatrix.clone();
  41039. invView.invert();
  41040. effect.setMatrix("invView", invView);
  41041. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41042. }
  41043. // VBOs
  41044. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41045. // Draw order
  41046. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  41047. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  41048. }
  41049. else {
  41050. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41051. }
  41052. if (this.forceDepthWrite) {
  41053. engine.setDepthWrite(true);
  41054. }
  41055. engine.draw(true, 0, this.particles.length * 6);
  41056. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41057. return this.particles.length;
  41058. };
  41059. ParticleSystem.prototype.dispose = function () {
  41060. if (this._vertexBuffer) {
  41061. this._vertexBuffer.dispose();
  41062. this._vertexBuffer = null;
  41063. }
  41064. if (this._indexBuffer) {
  41065. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41066. this._indexBuffer = null;
  41067. }
  41068. if (this.particleTexture) {
  41069. this.particleTexture.dispose();
  41070. this.particleTexture = null;
  41071. }
  41072. // Remove from scene
  41073. var index = this._scene.particleSystems.indexOf(this);
  41074. if (index > -1) {
  41075. this._scene.particleSystems.splice(index, 1);
  41076. }
  41077. // Callback
  41078. this.onDisposeObservable.notifyObservers(this);
  41079. this.onDisposeObservable.clear();
  41080. };
  41081. // Clone
  41082. ParticleSystem.prototype.clone = function (name, newEmitter) {
  41083. var custom = null;
  41084. var program = null;
  41085. if (this.customShader != null) {
  41086. program = this.customShader;
  41087. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41088. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41089. }
  41090. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  41091. result.customShader = program;
  41092. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  41093. if (newEmitter === undefined) {
  41094. newEmitter = this.emitter;
  41095. }
  41096. result.emitter = newEmitter;
  41097. if (this.particleTexture) {
  41098. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  41099. }
  41100. if (!this.preventAutoStart) {
  41101. result.start();
  41102. }
  41103. return result;
  41104. };
  41105. ParticleSystem.prototype.serialize = function () {
  41106. var serializationObject = {};
  41107. serializationObject.name = this.name;
  41108. serializationObject.id = this.id;
  41109. // Emitter
  41110. if (this.emitter.position) {
  41111. var emitterMesh = this.emitter;
  41112. serializationObject.emitterId = emitterMesh.id;
  41113. }
  41114. else {
  41115. var emitterPosition = this.emitter;
  41116. serializationObject.emitter = emitterPosition.asArray();
  41117. }
  41118. serializationObject.capacity = this.getCapacity();
  41119. if (this.particleTexture) {
  41120. serializationObject.textureName = this.particleTexture.name;
  41121. }
  41122. // Animations
  41123. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  41124. // Particle system
  41125. serializationObject.minAngularSpeed = this.minAngularSpeed;
  41126. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  41127. serializationObject.minSize = this.minSize;
  41128. serializationObject.maxSize = this.maxSize;
  41129. serializationObject.minEmitPower = this.minEmitPower;
  41130. serializationObject.maxEmitPower = this.maxEmitPower;
  41131. serializationObject.minLifeTime = this.minLifeTime;
  41132. serializationObject.maxLifeTime = this.maxLifeTime;
  41133. serializationObject.emitRate = this.emitRate;
  41134. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41135. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41136. serializationObject.gravity = this.gravity.asArray();
  41137. serializationObject.direction1 = this.direction1.asArray();
  41138. serializationObject.direction2 = this.direction2.asArray();
  41139. serializationObject.color1 = this.color1.asArray();
  41140. serializationObject.color2 = this.color2.asArray();
  41141. serializationObject.colorDead = this.colorDead.asArray();
  41142. serializationObject.updateSpeed = this.updateSpeed;
  41143. serializationObject.targetStopDuration = this.targetStopDuration;
  41144. serializationObject.textureMask = this.textureMask.asArray();
  41145. serializationObject.blendMode = this.blendMode;
  41146. serializationObject.customShader = this.customShader;
  41147. serializationObject.preventAutoStart = this.preventAutoStart;
  41148. return serializationObject;
  41149. };
  41150. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41151. var name = parsedParticleSystem.name;
  41152. var custom = null;
  41153. var program = null;
  41154. if (parsedParticleSystem.customShader) {
  41155. program = parsedParticleSystem.customShader;
  41156. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41157. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41158. }
  41159. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41160. particleSystem.customShader = program;
  41161. if (parsedParticleSystem.id) {
  41162. particleSystem.id = parsedParticleSystem.id;
  41163. }
  41164. // Auto start
  41165. if (parsedParticleSystem.preventAutoStart) {
  41166. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41167. }
  41168. // Texture
  41169. if (parsedParticleSystem.textureName) {
  41170. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41171. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41172. }
  41173. // Emitter
  41174. if (parsedParticleSystem.emitterId) {
  41175. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41176. }
  41177. else {
  41178. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41179. }
  41180. // Animations
  41181. if (parsedParticleSystem.animations) {
  41182. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41183. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41184. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41185. }
  41186. }
  41187. if (parsedParticleSystem.autoAnimate) {
  41188. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41189. }
  41190. // Particle system
  41191. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41192. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41193. particleSystem.minSize = parsedParticleSystem.minSize;
  41194. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41195. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41196. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41197. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41198. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41199. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41200. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41201. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41202. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41203. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41204. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41205. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41206. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41207. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41208. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41209. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41210. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41211. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41212. if (!particleSystem.preventAutoStart) {
  41213. particleSystem.start();
  41214. }
  41215. return particleSystem;
  41216. };
  41217. // Statics
  41218. ParticleSystem.BLENDMODE_ONEONE = 0;
  41219. ParticleSystem.BLENDMODE_STANDARD = 1;
  41220. return ParticleSystem;
  41221. }());
  41222. BABYLON.ParticleSystem = ParticleSystem;
  41223. })(BABYLON || (BABYLON = {}));
  41224. //# sourceMappingURL=babylon.particleSystem.js.map
  41225. var BABYLON;
  41226. (function (BABYLON) {
  41227. var SolidParticle = (function () {
  41228. /**
  41229. * Creates a Solid Particle object.
  41230. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41231. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41232. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41233. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41234. * `shapeId` (integer) is the model shape identifier in the SPS.
  41235. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41236. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41237. */
  41238. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41239. this.idx = 0; // particle global index
  41240. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41241. this.position = BABYLON.Vector3.Zero(); // position
  41242. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41243. this.scaling = BABYLON.Vector3.One(); // scaling
  41244. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41245. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41246. this.alive = true; // alive
  41247. this.isVisible = true; // visibility
  41248. this._pos = 0; // index of this particle in the global "positions" array
  41249. this.shapeId = 0; // model shape id
  41250. this.idxInShape = 0; // index of the particle in its shape id
  41251. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41252. this.idx = particleIndex;
  41253. this._pos = positionIndex;
  41254. this._model = model;
  41255. this.shapeId = shapeId;
  41256. this.idxInShape = idxInShape;
  41257. this._sps = sps;
  41258. if (modelBoundingInfo) {
  41259. this._modelBoundingInfo = modelBoundingInfo;
  41260. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41261. }
  41262. }
  41263. Object.defineProperty(SolidParticle.prototype, "scale", {
  41264. /**
  41265. * legacy support, changed scale to scaling
  41266. */
  41267. get: function () {
  41268. return this.scaling;
  41269. },
  41270. set: function (scale) {
  41271. this.scaling = scale;
  41272. },
  41273. enumerable: true,
  41274. configurable: true
  41275. });
  41276. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41277. /**
  41278. * legacy support, changed quaternion to rotationQuaternion
  41279. */
  41280. get: function () {
  41281. return this.rotationQuaternion;
  41282. },
  41283. set: function (q) {
  41284. this.rotationQuaternion = q;
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. /**
  41290. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41291. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41292. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41293. */
  41294. SolidParticle.prototype.intersectsMesh = function (target) {
  41295. if (!this._boundingInfo || !target._boundingInfo) {
  41296. return false;
  41297. }
  41298. if (this._sps._bSphereOnly) {
  41299. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41300. }
  41301. return this._boundingInfo.intersects(target._boundingInfo, false);
  41302. };
  41303. return SolidParticle;
  41304. }());
  41305. BABYLON.SolidParticle = SolidParticle;
  41306. var ModelShape = (function () {
  41307. /**
  41308. * 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.
  41309. * SPS internal tool, don't use it manually.
  41310. */
  41311. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41312. this.shapeID = id;
  41313. this._shape = shape;
  41314. this._shapeUV = shapeUV;
  41315. this._positionFunction = posFunction;
  41316. this._vertexFunction = vtxFunction;
  41317. }
  41318. return ModelShape;
  41319. }());
  41320. BABYLON.ModelShape = ModelShape;
  41321. })(BABYLON || (BABYLON = {}));
  41322. //# sourceMappingURL=babylon.solidParticle.js.map
  41323. var BABYLON;
  41324. (function (BABYLON) {
  41325. /**
  41326. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41327. */
  41328. var SolidParticleSystem = (function () {
  41329. /**
  41330. * Creates a SPS (Solid Particle System) object.
  41331. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41332. * `scene` (Scene) is the scene in which the SPS is added.
  41333. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41334. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41335. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41336. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41337. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41338. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41339. */
  41340. function SolidParticleSystem(name, scene, options) {
  41341. // public members
  41342. /**
  41343. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41344. * Example : var p = SPS.particles[i];
  41345. */
  41346. this.particles = new Array();
  41347. /**
  41348. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41349. */
  41350. this.nbParticles = 0;
  41351. /**
  41352. * If the particles must ever face the camera (default false). Useful for planar particles.
  41353. */
  41354. this.billboard = false;
  41355. /**
  41356. * Recompute normals when adding a shape
  41357. */
  41358. this.recomputeNormals = true;
  41359. /**
  41360. * This a counter ofr your own usage. It's not set by any SPS functions.
  41361. */
  41362. this.counter = 0;
  41363. /**
  41364. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41365. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41366. */
  41367. this.vars = {};
  41368. this._positions = new Array();
  41369. this._indices = new Array();
  41370. this._normals = new Array();
  41371. this._colors = new Array();
  41372. this._uvs = new Array();
  41373. this._index = 0; // indices index
  41374. this._updatable = true;
  41375. this._pickable = false;
  41376. this._isVisibilityBoxLocked = false;
  41377. this._alwaysVisible = false;
  41378. this._shapeCounter = 0;
  41379. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41380. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41381. this._computeParticleColor = true;
  41382. this._computeParticleTexture = true;
  41383. this._computeParticleRotation = true;
  41384. this._computeParticleVertex = false;
  41385. this._computeBoundingBox = false;
  41386. this._cam_axisZ = BABYLON.Vector3.Zero();
  41387. this._cam_axisY = BABYLON.Vector3.Zero();
  41388. this._cam_axisX = BABYLON.Vector3.Zero();
  41389. this._axisX = BABYLON.Axis.X;
  41390. this._axisY = BABYLON.Axis.Y;
  41391. this._axisZ = BABYLON.Axis.Z;
  41392. this._camDir = BABYLON.Vector3.Zero();
  41393. this._rotMatrix = new BABYLON.Matrix();
  41394. this._invertMatrix = new BABYLON.Matrix();
  41395. this._rotated = BABYLON.Vector3.Zero();
  41396. this._quaternion = new BABYLON.Quaternion();
  41397. this._vertex = BABYLON.Vector3.Zero();
  41398. this._normal = BABYLON.Vector3.Zero();
  41399. this._yaw = 0.0;
  41400. this._pitch = 0.0;
  41401. this._roll = 0.0;
  41402. this._halfroll = 0.0;
  41403. this._halfpitch = 0.0;
  41404. this._halfyaw = 0.0;
  41405. this._sinRoll = 0.0;
  41406. this._cosRoll = 0.0;
  41407. this._sinPitch = 0.0;
  41408. this._cosPitch = 0.0;
  41409. this._sinYaw = 0.0;
  41410. this._cosYaw = 0.0;
  41411. this._w = 0.0;
  41412. this._mustUnrotateFixedNormals = false;
  41413. this._minimum = BABYLON.Tmp.Vector3[0];
  41414. this._maximum = BABYLON.Tmp.Vector3[1];
  41415. this._scale = BABYLON.Tmp.Vector3[2];
  41416. this._translation = BABYLON.Tmp.Vector3[3];
  41417. this._minBbox = BABYLON.Tmp.Vector3[4];
  41418. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41419. this._particlesIntersect = false;
  41420. this._bSphereOnly = false;
  41421. this._bSphereRadiusFactor = 1.0;
  41422. this.name = name;
  41423. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41424. this._camera = scene.activeCamera;
  41425. this._pickable = options ? options.isPickable : false;
  41426. this._particlesIntersect = options ? options.particleIntersection : false;
  41427. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41428. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41429. if (options && options.updatable) {
  41430. this._updatable = options.updatable;
  41431. }
  41432. else {
  41433. this._updatable = true;
  41434. }
  41435. if (this._pickable) {
  41436. this.pickedParticles = [];
  41437. }
  41438. }
  41439. /**
  41440. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41441. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41442. */
  41443. SolidParticleSystem.prototype.buildMesh = function () {
  41444. if (this.nbParticles === 0) {
  41445. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41446. this.addShape(triangle, 1);
  41447. triangle.dispose();
  41448. }
  41449. this._positions32 = new Float32Array(this._positions);
  41450. this._uvs32 = new Float32Array(this._uvs);
  41451. this._colors32 = new Float32Array(this._colors);
  41452. if (this.recomputeNormals) {
  41453. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41454. }
  41455. this._normals32 = new Float32Array(this._normals);
  41456. this._fixedNormal32 = new Float32Array(this._normals);
  41457. if (this._mustUnrotateFixedNormals) {
  41458. this._unrotateFixedNormals();
  41459. }
  41460. var vertexData = new BABYLON.VertexData();
  41461. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41462. vertexData.indices = this._indices;
  41463. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41464. if (this._uvs32) {
  41465. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41466. ;
  41467. }
  41468. if (this._colors32) {
  41469. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41470. }
  41471. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41472. vertexData.applyToMesh(mesh, this._updatable);
  41473. this.mesh = mesh;
  41474. this.mesh.isPickable = this._pickable;
  41475. // free memory
  41476. this._positions = null;
  41477. this._normals = null;
  41478. this._uvs = null;
  41479. this._colors = null;
  41480. if (!this._updatable) {
  41481. this.particles.length = 0;
  41482. }
  41483. return mesh;
  41484. };
  41485. /**
  41486. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41487. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41488. * Thus the particles generated from `digest()` have their property `position` set yet.
  41489. * `mesh` ( Mesh ) is the mesh to be digested
  41490. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41491. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41492. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41493. */
  41494. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41495. var size = (options && options.facetNb) || 1;
  41496. var number = (options && options.number);
  41497. var delta = (options && options.delta) || 0;
  41498. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41499. var meshInd = mesh.getIndices();
  41500. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41501. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41502. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41503. var f = 0; // facet counter
  41504. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41505. // compute size from number
  41506. if (number) {
  41507. number = (number > totalFacets) ? totalFacets : number;
  41508. size = Math.round(totalFacets / number);
  41509. delta = 0;
  41510. }
  41511. else {
  41512. size = (size > totalFacets) ? totalFacets : size;
  41513. }
  41514. var facetPos = []; // submesh positions
  41515. var facetInd = []; // submesh indices
  41516. var facetUV = []; // submesh UV
  41517. var facetCol = []; // submesh colors
  41518. var barycenter = BABYLON.Tmp.Vector3[0];
  41519. var rand;
  41520. var sizeO = size;
  41521. while (f < totalFacets) {
  41522. size = sizeO + Math.floor((1 + delta) * Math.random());
  41523. if (f > totalFacets - size) {
  41524. size = totalFacets - f;
  41525. }
  41526. // reset temp arrays
  41527. facetPos.length = 0;
  41528. facetInd.length = 0;
  41529. facetUV.length = 0;
  41530. facetCol.length = 0;
  41531. // iterate over "size" facets
  41532. var fi = 0;
  41533. for (var j = f * 3; j < (f + size) * 3; j++) {
  41534. facetInd.push(fi);
  41535. var i = meshInd[j];
  41536. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41537. if (meshUV) {
  41538. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41539. }
  41540. if (meshCol) {
  41541. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41542. }
  41543. fi++;
  41544. }
  41545. // create a model shape for each single particle
  41546. var idx = this.nbParticles;
  41547. var shape = this._posToShape(facetPos);
  41548. var shapeUV = this._uvsToShapeUV(facetUV);
  41549. // compute the barycenter of the shape
  41550. var v;
  41551. for (v = 0; v < shape.length; v++) {
  41552. barycenter.addInPlace(shape[v]);
  41553. }
  41554. barycenter.scaleInPlace(1 / shape.length);
  41555. // shift the shape from its barycenter to the origin
  41556. for (v = 0; v < shape.length; v++) {
  41557. shape[v].subtractInPlace(barycenter);
  41558. }
  41559. var bInfo;
  41560. if (this._particlesIntersect) {
  41561. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  41562. }
  41563. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41564. // add the particle in the SPS
  41565. var currentPos = this._positions.length;
  41566. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  41567. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  41568. // initialize the particle position
  41569. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41570. this._index += shape.length;
  41571. idx++;
  41572. this.nbParticles++;
  41573. this._shapeCounter++;
  41574. f += size;
  41575. }
  41576. return this;
  41577. };
  41578. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  41579. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  41580. var index = 0;
  41581. var idx = 0;
  41582. for (var p = 0; p < this.particles.length; p++) {
  41583. this._particle = this.particles[p];
  41584. this._shape = this._particle._model._shape;
  41585. if (this._particle.rotationQuaternion) {
  41586. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41587. }
  41588. else {
  41589. this._yaw = this._particle.rotation.y;
  41590. this._pitch = this._particle.rotation.x;
  41591. this._roll = this._particle.rotation.z;
  41592. this._quaternionRotationYPR();
  41593. }
  41594. this._quaternionToRotationMatrix();
  41595. this._rotMatrix.invertToRef(this._invertMatrix);
  41596. for (var pt = 0; pt < this._shape.length; pt++) {
  41597. idx = index + pt * 3;
  41598. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41599. this._fixedNormal32[idx] = this._normal.x;
  41600. this._fixedNormal32[idx + 1] = this._normal.y;
  41601. this._fixedNormal32[idx + 2] = this._normal.z;
  41602. }
  41603. index = idx + 3;
  41604. }
  41605. };
  41606. //reset copy
  41607. SolidParticleSystem.prototype._resetCopy = function () {
  41608. this._copy.position.x = 0;
  41609. this._copy.position.y = 0;
  41610. this._copy.position.z = 0;
  41611. this._copy.rotation.x = 0;
  41612. this._copy.rotation.y = 0;
  41613. this._copy.rotation.z = 0;
  41614. this._copy.rotationQuaternion = null;
  41615. this._copy.scaling.x = 1;
  41616. this._copy.scaling.y = 1;
  41617. this._copy.scaling.z = 1;
  41618. this._copy.uvs.x = 0;
  41619. this._copy.uvs.y = 0;
  41620. this._copy.uvs.z = 1;
  41621. this._copy.uvs.w = 1;
  41622. this._copy.color = null;
  41623. };
  41624. // _meshBuilder : inserts the shape model in the global SPS mesh
  41625. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41626. var i;
  41627. var u = 0;
  41628. var c = 0;
  41629. var n = 0;
  41630. this._resetCopy();
  41631. if (options && options.positionFunction) {
  41632. options.positionFunction(this._copy, idx, idxInShape);
  41633. this._mustUnrotateFixedNormals = true;
  41634. }
  41635. if (this._copy.rotationQuaternion) {
  41636. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41637. }
  41638. else {
  41639. this._yaw = this._copy.rotation.y;
  41640. this._pitch = this._copy.rotation.x;
  41641. this._roll = this._copy.rotation.z;
  41642. this._quaternionRotationYPR();
  41643. }
  41644. this._quaternionToRotationMatrix();
  41645. for (i = 0; i < shape.length; i++) {
  41646. this._vertex.x = shape[i].x;
  41647. this._vertex.y = shape[i].y;
  41648. this._vertex.z = shape[i].z;
  41649. if (options && options.vertexFunction) {
  41650. options.vertexFunction(this._copy, this._vertex, i);
  41651. }
  41652. this._vertex.x *= this._copy.scaling.x;
  41653. this._vertex.y *= this._copy.scaling.y;
  41654. this._vertex.z *= this._copy.scaling.z;
  41655. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41656. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41657. if (meshUV) {
  41658. 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);
  41659. u += 2;
  41660. }
  41661. if (this._copy.color) {
  41662. this._color = this._copy.color;
  41663. }
  41664. else if (meshCol && meshCol[c] !== undefined) {
  41665. this._color.r = meshCol[c];
  41666. this._color.g = meshCol[c + 1];
  41667. this._color.b = meshCol[c + 2];
  41668. this._color.a = meshCol[c + 3];
  41669. }
  41670. else {
  41671. this._color.r = 1;
  41672. this._color.g = 1;
  41673. this._color.b = 1;
  41674. this._color.a = 1;
  41675. }
  41676. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41677. c += 4;
  41678. if (!this.recomputeNormals && meshNor) {
  41679. this._normal.x = meshNor[n];
  41680. this._normal.y = meshNor[n + 1];
  41681. this._normal.z = meshNor[n + 2];
  41682. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41683. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41684. n += 3;
  41685. }
  41686. }
  41687. for (i = 0; i < meshInd.length; i++) {
  41688. indices.push(p + meshInd[i]);
  41689. }
  41690. if (this._pickable) {
  41691. var nbfaces = meshInd.length / 3;
  41692. for (i = 0; i < nbfaces; i++) {
  41693. this.pickedParticles.push({ idx: idx, faceId: i });
  41694. }
  41695. }
  41696. return this._copy;
  41697. };
  41698. // returns a shape array from positions array
  41699. SolidParticleSystem.prototype._posToShape = function (positions) {
  41700. var shape = [];
  41701. for (var i = 0; i < positions.length; i += 3) {
  41702. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41703. }
  41704. return shape;
  41705. };
  41706. // returns a shapeUV array from a Vector4 uvs
  41707. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41708. var shapeUV = [];
  41709. if (uvs) {
  41710. for (var i = 0; i < uvs.length; i++)
  41711. shapeUV.push(uvs[i]);
  41712. }
  41713. return shapeUV;
  41714. };
  41715. // adds a new particle object in the particles array
  41716. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41717. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41718. this.particles.push(sp);
  41719. return sp;
  41720. };
  41721. /**
  41722. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41723. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41724. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41725. * `nb` (positive integer) the number of particles to be created from this model
  41726. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41727. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41728. */
  41729. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41730. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41731. var meshInd = mesh.getIndices();
  41732. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41733. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41734. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41735. var bbInfo;
  41736. if (this._particlesIntersect) {
  41737. bbInfo = mesh.getBoundingInfo();
  41738. }
  41739. var shape = this._posToShape(meshPos);
  41740. var shapeUV = this._uvsToShapeUV(meshUV);
  41741. var posfunc = options ? options.positionFunction : null;
  41742. var vtxfunc = options ? options.vertexFunction : null;
  41743. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41744. // particles
  41745. var sp;
  41746. var currentCopy;
  41747. var idx = this.nbParticles;
  41748. for (var i = 0; i < nb; i++) {
  41749. var currentPos = this._positions.length;
  41750. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41751. if (this._updatable) {
  41752. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41753. sp.position.copyFrom(currentCopy.position);
  41754. sp.rotation.copyFrom(currentCopy.rotation);
  41755. if (currentCopy.rotationQuaternion) {
  41756. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41757. }
  41758. if (currentCopy.color) {
  41759. sp.color.copyFrom(currentCopy.color);
  41760. }
  41761. sp.scaling.copyFrom(currentCopy.scaling);
  41762. sp.uvs.copyFrom(currentCopy.uvs);
  41763. }
  41764. this._index += shape.length;
  41765. idx++;
  41766. }
  41767. this.nbParticles += nb;
  41768. this._shapeCounter++;
  41769. return this._shapeCounter - 1;
  41770. };
  41771. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41772. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41773. this._resetCopy();
  41774. if (particle._model._positionFunction) {
  41775. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41776. }
  41777. if (this._copy.rotationQuaternion) {
  41778. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41779. }
  41780. else {
  41781. this._yaw = this._copy.rotation.y;
  41782. this._pitch = this._copy.rotation.x;
  41783. this._roll = this._copy.rotation.z;
  41784. this._quaternionRotationYPR();
  41785. }
  41786. this._quaternionToRotationMatrix();
  41787. this._shape = particle._model._shape;
  41788. for (var pt = 0; pt < this._shape.length; pt++) {
  41789. this._vertex.x = this._shape[pt].x;
  41790. this._vertex.y = this._shape[pt].y;
  41791. this._vertex.z = this._shape[pt].z;
  41792. if (particle._model._vertexFunction) {
  41793. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41794. }
  41795. this._vertex.x *= this._copy.scaling.x;
  41796. this._vertex.y *= this._copy.scaling.y;
  41797. this._vertex.z *= this._copy.scaling.z;
  41798. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41799. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41800. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41801. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41802. }
  41803. particle.position.x = 0.0;
  41804. particle.position.y = 0.0;
  41805. particle.position.z = 0.0;
  41806. particle.rotation.x = 0.0;
  41807. particle.rotation.y = 0.0;
  41808. particle.rotation.z = 0.0;
  41809. particle.rotationQuaternion = null;
  41810. particle.scaling.x = 1.0;
  41811. particle.scaling.y = 1.0;
  41812. particle.scaling.z = 1.0;
  41813. };
  41814. /**
  41815. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41816. * Returns the SPS.
  41817. */
  41818. SolidParticleSystem.prototype.rebuildMesh = function () {
  41819. for (var p = 0; p < this.particles.length; p++) {
  41820. this._rebuildParticle(this.particles[p]);
  41821. }
  41822. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41823. return this;
  41824. };
  41825. /**
  41826. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41827. * This method calls `updateParticle()` for each particle of the SPS.
  41828. * For an animated SPS, it is usually called within the render loop.
  41829. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  41830. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  41831. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  41832. * Returns the SPS.
  41833. */
  41834. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41835. if (start === void 0) { start = 0; }
  41836. if (end === void 0) { end = this.nbParticles - 1; }
  41837. if (update === void 0) { update = true; }
  41838. if (!this._updatable) {
  41839. return;
  41840. }
  41841. // custom beforeUpdate
  41842. this.beforeUpdateParticles(start, end, update);
  41843. this._cam_axisX.x = 1.0;
  41844. this._cam_axisX.y = 0.0;
  41845. this._cam_axisX.z = 0.0;
  41846. this._cam_axisY.x = 0.0;
  41847. this._cam_axisY.y = 1.0;
  41848. this._cam_axisY.z = 0.0;
  41849. this._cam_axisZ.x = 0.0;
  41850. this._cam_axisZ.y = 0.0;
  41851. this._cam_axisZ.z = 1.0;
  41852. // if the particles will always face the camera
  41853. if (this.billboard) {
  41854. this.mesh.computeWorldMatrix(true);
  41855. // compute the camera position and un-rotate it by the current mesh rotation
  41856. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  41857. this._quaternionToRotationMatrix();
  41858. this._rotMatrix.invertToRef(this._invertMatrix);
  41859. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  41860. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  41861. this._cam_axisZ.normalize();
  41862. // same for camera up vector extracted from the cam view matrix
  41863. var view = this._camera.getViewMatrix(true);
  41864. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  41865. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  41866. this._cam_axisY.normalize();
  41867. this._cam_axisX.normalize();
  41868. }
  41869. }
  41870. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41871. var idx = 0; // current position index in the global array positions32
  41872. var index = 0; // position start index in the global array positions32 of the current particle
  41873. var colidx = 0; // current color index in the global array colors32
  41874. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  41875. var uvidx = 0; // current uv index in the global array uvs32
  41876. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  41877. var pt = 0; // current index in the particle model shape
  41878. if (this.mesh.isFacetDataEnabled) {
  41879. this._computeBoundingBox = true;
  41880. }
  41881. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  41882. if (this._computeBoundingBox) {
  41883. if (start == 0 && end == this.nbParticles - 1) {
  41884. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41885. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41886. }
  41887. else {
  41888. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  41889. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  41890. }
  41891. }
  41892. // particle loop
  41893. index = this.particles[start]._pos;
  41894. var vpos = (index / 3) | 0;
  41895. colorIndex = vpos * 4;
  41896. uvIndex = vpos * 2;
  41897. for (var p = start; p <= end; p++) {
  41898. this._particle = this.particles[p];
  41899. this._shape = this._particle._model._shape;
  41900. this._shapeUV = this._particle._model._shapeUV;
  41901. // call to custom user function to update the particle properties
  41902. this.updateParticle(this._particle);
  41903. // skip the computations for inactive or already invisible particles
  41904. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  41905. // increment indexes for the next particle
  41906. pt = this._shape.length;
  41907. index += pt * 3;
  41908. colorIndex += pt * 4;
  41909. uvIndex += pt * 2;
  41910. continue;
  41911. }
  41912. if (this._particle.isVisible) {
  41913. this._particle._stillInvisible = false; // un-mark permanent invisibility
  41914. // particle rotation matrix
  41915. if (this.billboard) {
  41916. this._particle.rotation.x = 0.0;
  41917. this._particle.rotation.y = 0.0;
  41918. }
  41919. if (this._computeParticleRotation || this.billboard) {
  41920. if (this._particle.rotationQuaternion) {
  41921. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41922. }
  41923. else {
  41924. this._yaw = this._particle.rotation.y;
  41925. this._pitch = this._particle.rotation.x;
  41926. this._roll = this._particle.rotation.z;
  41927. this._quaternionRotationYPR();
  41928. }
  41929. this._quaternionToRotationMatrix();
  41930. }
  41931. // particle vertex loop
  41932. for (pt = 0; pt < this._shape.length; pt++) {
  41933. idx = index + pt * 3;
  41934. colidx = colorIndex + pt * 4;
  41935. uvidx = uvIndex + pt * 2;
  41936. this._vertex.x = this._shape[pt].x;
  41937. this._vertex.y = this._shape[pt].y;
  41938. this._vertex.z = this._shape[pt].z;
  41939. if (this._computeParticleVertex) {
  41940. this.updateParticleVertex(this._particle, this._vertex, pt);
  41941. }
  41942. // positions
  41943. this._vertex.x *= this._particle.scaling.x;
  41944. this._vertex.y *= this._particle.scaling.y;
  41945. this._vertex.z *= this._particle.scaling.z;
  41946. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  41947. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  41948. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  41949. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  41950. 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;
  41951. 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;
  41952. 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;
  41953. if (this._computeBoundingBox) {
  41954. if (this._positions32[idx] < this._minimum.x) {
  41955. this._minimum.x = this._positions32[idx];
  41956. }
  41957. if (this._positions32[idx] > this._maximum.x) {
  41958. this._maximum.x = this._positions32[idx];
  41959. }
  41960. if (this._positions32[idx + 1] < this._minimum.y) {
  41961. this._minimum.y = this._positions32[idx + 1];
  41962. }
  41963. if (this._positions32[idx + 1] > this._maximum.y) {
  41964. this._maximum.y = this._positions32[idx + 1];
  41965. }
  41966. if (this._positions32[idx + 2] < this._minimum.z) {
  41967. this._minimum.z = this._positions32[idx + 2];
  41968. }
  41969. if (this._positions32[idx + 2] > this._maximum.z) {
  41970. this._maximum.z = this._positions32[idx + 2];
  41971. }
  41972. }
  41973. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  41974. if (!this._computeParticleVertex) {
  41975. this._normal.x = this._fixedNormal32[idx];
  41976. this._normal.y = this._fixedNormal32[idx + 1];
  41977. this._normal.z = this._fixedNormal32[idx + 2];
  41978. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]);
  41979. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]);
  41980. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]);
  41981. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41982. 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;
  41983. 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;
  41984. }
  41985. if (this._computeParticleColor) {
  41986. this._colors32[colidx] = this._particle.color.r;
  41987. this._colors32[colidx + 1] = this._particle.color.g;
  41988. this._colors32[colidx + 2] = this._particle.color.b;
  41989. this._colors32[colidx + 3] = this._particle.color.a;
  41990. }
  41991. if (this._computeParticleTexture) {
  41992. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41993. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41994. }
  41995. }
  41996. }
  41997. else {
  41998. this._particle._stillInvisible = true; // mark the particle as invisible
  41999. for (pt = 0; pt < this._shape.length; pt++) {
  42000. idx = index + pt * 3;
  42001. colidx = colorIndex + pt * 4;
  42002. uvidx = uvIndex + pt * 2;
  42003. this._positions32[idx] = 0.0;
  42004. this._positions32[idx + 1] = 0.0;
  42005. this._positions32[idx + 2] = 0.0;
  42006. this._normals32[idx] = 0.0;
  42007. this._normals32[idx + 1] = 0.0;
  42008. this._normals32[idx + 2] = 0.0;
  42009. if (this._computeParticleColor) {
  42010. this._colors32[colidx] = this._particle.color.r;
  42011. this._colors32[colidx + 1] = this._particle.color.g;
  42012. this._colors32[colidx + 2] = this._particle.color.b;
  42013. this._colors32[colidx + 3] = this._particle.color.a;
  42014. }
  42015. if (this._computeParticleTexture) {
  42016. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42017. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42018. }
  42019. }
  42020. }
  42021. // if the particle intersections must be computed : update the bbInfo
  42022. if (this._particlesIntersect) {
  42023. var bInfo = this._particle._boundingInfo;
  42024. var bBox = bInfo.boundingBox;
  42025. var bSphere = bInfo.boundingSphere;
  42026. if (!this._bSphereOnly) {
  42027. // place, scale and rotate the particle bbox within the SPS local system, then update it
  42028. for (var b = 0; b < bBox.vectors.length; b++) {
  42029. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  42030. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  42031. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  42032. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  42033. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  42034. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  42035. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  42036. 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;
  42037. 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;
  42038. 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;
  42039. }
  42040. bBox._update(this.mesh._worldMatrix);
  42041. }
  42042. // place and scale the particle bouding sphere in the SPS local system, then update it
  42043. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  42044. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  42045. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  42046. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  42047. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  42048. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  42049. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  42050. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  42051. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  42052. 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));
  42053. bSphere._update(this.mesh._worldMatrix);
  42054. }
  42055. // increment indexes for the next particle
  42056. index = idx + 3;
  42057. colorIndex = colidx + 4;
  42058. uvIndex = uvidx + 2;
  42059. }
  42060. // if the VBO must be updated
  42061. if (update) {
  42062. if (this._computeParticleColor) {
  42063. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42064. }
  42065. if (this._computeParticleTexture) {
  42066. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42067. }
  42068. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42069. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  42070. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  42071. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  42072. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  42073. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  42074. for (var i = 0; i < this._normals32.length; i++) {
  42075. this._fixedNormal32[i] = this._normals32[i];
  42076. }
  42077. }
  42078. if (!this.mesh.areNormalsFrozen) {
  42079. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42080. }
  42081. }
  42082. }
  42083. if (this._computeBoundingBox) {
  42084. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42085. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42086. }
  42087. this.afterUpdateParticles(start, end, update);
  42088. return this;
  42089. };
  42090. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42091. this._halfroll = this._roll * 0.5;
  42092. this._halfpitch = this._pitch * 0.5;
  42093. this._halfyaw = this._yaw * 0.5;
  42094. this._sinRoll = Math.sin(this._halfroll);
  42095. this._cosRoll = Math.cos(this._halfroll);
  42096. this._sinPitch = Math.sin(this._halfpitch);
  42097. this._cosPitch = Math.cos(this._halfpitch);
  42098. this._sinYaw = Math.sin(this._halfyaw);
  42099. this._cosYaw = Math.cos(this._halfyaw);
  42100. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42101. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42102. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42103. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42104. };
  42105. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42106. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42107. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42108. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42109. this._rotMatrix.m[3] = 0;
  42110. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42111. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42112. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42113. this._rotMatrix.m[7] = 0;
  42114. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42115. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42116. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42117. this._rotMatrix.m[11] = 0;
  42118. this._rotMatrix.m[12] = 0;
  42119. this._rotMatrix.m[13] = 0;
  42120. this._rotMatrix.m[14] = 0;
  42121. this._rotMatrix.m[15] = 1.0;
  42122. };
  42123. /**
  42124. * Disposes the SPS.
  42125. * Returns nothing.
  42126. */
  42127. SolidParticleSystem.prototype.dispose = function () {
  42128. this.mesh.dispose();
  42129. this.vars = null;
  42130. // drop references to internal big arrays for the GC
  42131. this._positions = null;
  42132. this._indices = null;
  42133. this._normals = null;
  42134. this._uvs = null;
  42135. this._colors = null;
  42136. this._positions32 = null;
  42137. this._normals32 = null;
  42138. this._fixedNormal32 = null;
  42139. this._uvs32 = null;
  42140. this._colors32 = null;
  42141. this.pickedParticles = null;
  42142. };
  42143. /**
  42144. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42145. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42146. * Returns the SPS.
  42147. */
  42148. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42149. if (!this._isVisibilityBoxLocked) {
  42150. this.mesh.refreshBoundingInfo();
  42151. }
  42152. return this;
  42153. };
  42154. /**
  42155. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42156. * @param size the size (float) of the visibility box
  42157. * note : this doesn't lock the SPS mesh bounding box.
  42158. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42159. */
  42160. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42161. var vis = size / 2;
  42162. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42163. };
  42164. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42165. // getter and setter
  42166. get: function () {
  42167. return this._alwaysVisible;
  42168. },
  42169. /**
  42170. * Sets the SPS as always visible or not
  42171. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42172. */
  42173. set: function (val) {
  42174. this._alwaysVisible = val;
  42175. this.mesh.alwaysSelectAsActiveMesh = val;
  42176. },
  42177. enumerable: true,
  42178. configurable: true
  42179. });
  42180. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42181. get: function () {
  42182. return this._isVisibilityBoxLocked;
  42183. },
  42184. /**
  42185. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42186. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42187. */
  42188. set: function (val) {
  42189. this._isVisibilityBoxLocked = val;
  42190. this.mesh.getBoundingInfo().isLocked = val;
  42191. },
  42192. enumerable: true,
  42193. configurable: true
  42194. });
  42195. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42196. // getters
  42197. get: function () {
  42198. return this._computeParticleRotation;
  42199. },
  42200. // Optimizer setters
  42201. /**
  42202. * Tells to `setParticles()` to compute the particle rotations or not.
  42203. * Default value : true. The SPS is faster when it's set to false.
  42204. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42205. */
  42206. set: function (val) {
  42207. this._computeParticleRotation = val;
  42208. },
  42209. enumerable: true,
  42210. configurable: true
  42211. });
  42212. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42213. get: function () {
  42214. return this._computeParticleColor;
  42215. },
  42216. /**
  42217. * Tells to `setParticles()` to compute the particle colors or not.
  42218. * Default value : true. The SPS is faster when it's set to false.
  42219. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42220. */
  42221. set: function (val) {
  42222. this._computeParticleColor = val;
  42223. },
  42224. enumerable: true,
  42225. configurable: true
  42226. });
  42227. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42228. get: function () {
  42229. return this._computeParticleTexture;
  42230. },
  42231. /**
  42232. * Tells to `setParticles()` to compute the particle textures or not.
  42233. * Default value : true. The SPS is faster when it's set to false.
  42234. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42235. */
  42236. set: function (val) {
  42237. this._computeParticleTexture = val;
  42238. },
  42239. enumerable: true,
  42240. configurable: true
  42241. });
  42242. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42243. get: function () {
  42244. return this._computeParticleVertex;
  42245. },
  42246. /**
  42247. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42248. * Default value : false. The SPS is faster when it's set to false.
  42249. * Note : the particle custom vertex positions aren't stored values.
  42250. */
  42251. set: function (val) {
  42252. this._computeParticleVertex = val;
  42253. },
  42254. enumerable: true,
  42255. configurable: true
  42256. });
  42257. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42258. get: function () {
  42259. return this._computeBoundingBox;
  42260. },
  42261. /**
  42262. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42263. */
  42264. set: function (val) {
  42265. this._computeBoundingBox = val;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. // =======================================================================
  42271. // Particle behavior logic
  42272. // these following methods may be overwritten by the user to fit his needs
  42273. /**
  42274. * This function does nothing. It may be overwritten to set all the particle first values.
  42275. * The SPS doesn't call this function, you may have to call it by your own.
  42276. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42277. */
  42278. SolidParticleSystem.prototype.initParticles = function () {
  42279. };
  42280. /**
  42281. * This function does nothing. It may be overwritten to recycle a particle.
  42282. * The SPS doesn't call this function, you may have to call it by your own.
  42283. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42284. */
  42285. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42286. return particle;
  42287. };
  42288. /**
  42289. * Updates a particle : this function should be overwritten by the user.
  42290. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42291. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42292. * ex : just set a particle position or velocity and recycle conditions
  42293. */
  42294. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42295. return particle;
  42296. };
  42297. /**
  42298. * Updates a vertex of a particle : it can be overwritten by the user.
  42299. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42300. * @param particle the current particle
  42301. * @param vertex the current index of the current particle
  42302. * @param pt the index of the current vertex in the particle shape
  42303. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42304. * ex : just set a vertex particle position
  42305. */
  42306. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42307. return vertex;
  42308. };
  42309. /**
  42310. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42311. * This does nothing and may be overwritten by the user.
  42312. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42313. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42314. * @param update the boolean update value actually passed to setParticles()
  42315. */
  42316. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42317. };
  42318. /**
  42319. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42320. * This will be passed three parameters.
  42321. * This does nothing and may be overwritten by the user.
  42322. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42323. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42324. * @param update the boolean update value actually passed to setParticles()
  42325. */
  42326. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42327. };
  42328. return SolidParticleSystem;
  42329. }());
  42330. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42331. })(BABYLON || (BABYLON = {}));
  42332. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42333. /// <reference path="babylon.mesh.ts" />
  42334. var BABYLON;
  42335. (function (BABYLON) {
  42336. var GroundMesh = (function (_super) {
  42337. __extends(GroundMesh, _super);
  42338. function GroundMesh(name, scene) {
  42339. var _this = _super.call(this, name, scene) || this;
  42340. _this.generateOctree = false;
  42341. _this._worldInverse = new BABYLON.Matrix();
  42342. return _this;
  42343. }
  42344. GroundMesh.prototype.getClassName = function () {
  42345. return "GroundMesh";
  42346. };
  42347. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42348. get: function () {
  42349. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42350. },
  42351. enumerable: true,
  42352. configurable: true
  42353. });
  42354. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42355. get: function () {
  42356. return this._subdivisionsX;
  42357. },
  42358. enumerable: true,
  42359. configurable: true
  42360. });
  42361. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42362. get: function () {
  42363. return this._subdivisionsY;
  42364. },
  42365. enumerable: true,
  42366. configurable: true
  42367. });
  42368. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42369. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42370. this._subdivisionsX = chunksCount;
  42371. this._subdivisionsY = chunksCount;
  42372. this.subdivide(chunksCount);
  42373. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42374. };
  42375. /**
  42376. * Returns a height (y) value in the Worl system :
  42377. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42378. * Returns the ground y position if (x, z) are outside the ground surface.
  42379. */
  42380. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42381. var world = this.getWorldMatrix();
  42382. var invMat = BABYLON.Tmp.Matrix[5];
  42383. world.invertToRef(invMat);
  42384. var tmpVect = BABYLON.Tmp.Vector3[8];
  42385. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42386. x = tmpVect.x;
  42387. z = tmpVect.z;
  42388. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42389. return this.position.y;
  42390. }
  42391. if (!this._heightQuads || this._heightQuads.length == 0) {
  42392. this._initHeightQuads();
  42393. this._computeHeightQuads();
  42394. }
  42395. var facet = this._getFacetAt(x, z);
  42396. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42397. // return y in the World system
  42398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42399. return tmpVect.y;
  42400. };
  42401. /**
  42402. * Returns a normalized vector (Vector3) orthogonal to the ground
  42403. * at the ground coordinates (x, z) expressed in the World system.
  42404. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42405. */
  42406. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42407. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42408. this.getNormalAtCoordinatesToRef(x, z, normal);
  42409. return normal;
  42410. };
  42411. /**
  42412. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42413. * at the ground coordinates (x, z) expressed in the World system.
  42414. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42415. * Returns the GroundMesh.
  42416. */
  42417. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42418. var world = this.getWorldMatrix();
  42419. var tmpMat = BABYLON.Tmp.Matrix[5];
  42420. world.invertToRef(tmpMat);
  42421. var tmpVect = BABYLON.Tmp.Vector3[8];
  42422. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42423. x = tmpVect.x;
  42424. z = tmpVect.z;
  42425. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42426. return this;
  42427. }
  42428. if (!this._heightQuads || this._heightQuads.length == 0) {
  42429. this._initHeightQuads();
  42430. this._computeHeightQuads();
  42431. }
  42432. var facet = this._getFacetAt(x, z);
  42433. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42434. return this;
  42435. };
  42436. /**
  42437. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42438. * if the ground has been updated.
  42439. * This can be used in the render loop.
  42440. * Returns the GroundMesh.
  42441. */
  42442. GroundMesh.prototype.updateCoordinateHeights = function () {
  42443. if (!this._heightQuads || this._heightQuads.length == 0) {
  42444. this._initHeightQuads();
  42445. }
  42446. this._computeHeightQuads();
  42447. return this;
  42448. };
  42449. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42450. GroundMesh.prototype._getFacetAt = function (x, z) {
  42451. // retrieve col and row from x, z coordinates in the ground local system
  42452. var subdivisionsX = this._subdivisionsX;
  42453. var subdivisionsY = this._subdivisionsY;
  42454. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42455. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42456. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42457. var facet;
  42458. if (z < quad.slope.x * x + quad.slope.y) {
  42459. facet = quad.facet1;
  42460. }
  42461. else {
  42462. facet = quad.facet2;
  42463. }
  42464. return facet;
  42465. };
  42466. // Creates and populates the heightMap array with "facet" elements :
  42467. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42468. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42469. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42470. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42471. // Returns the GroundMesh.
  42472. GroundMesh.prototype._initHeightQuads = function () {
  42473. var subdivisionsX = this._subdivisionsX;
  42474. var subdivisionsY = this._subdivisionsY;
  42475. this._heightQuads = new Array();
  42476. for (var row = 0; row < subdivisionsY; row++) {
  42477. for (var col = 0; col < subdivisionsX; col++) {
  42478. 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) };
  42479. this._heightQuads[row * subdivisionsX + col] = quad;
  42480. }
  42481. }
  42482. return this;
  42483. };
  42484. // Compute each quad element values and update the the heightMap array :
  42485. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42486. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42487. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42488. // Returns the GroundMesh.
  42489. GroundMesh.prototype._computeHeightQuads = function () {
  42490. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42491. var v1 = BABYLON.Tmp.Vector3[3];
  42492. var v2 = BABYLON.Tmp.Vector3[2];
  42493. var v3 = BABYLON.Tmp.Vector3[1];
  42494. var v4 = BABYLON.Tmp.Vector3[0];
  42495. var v1v2 = BABYLON.Tmp.Vector3[4];
  42496. var v1v3 = BABYLON.Tmp.Vector3[5];
  42497. var v1v4 = BABYLON.Tmp.Vector3[6];
  42498. var norm1 = BABYLON.Tmp.Vector3[7];
  42499. var norm2 = BABYLON.Tmp.Vector3[8];
  42500. var i = 0;
  42501. var j = 0;
  42502. var k = 0;
  42503. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42504. var h = 0;
  42505. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42506. var d2 = 0;
  42507. var subdivisionsX = this._subdivisionsX;
  42508. var subdivisionsY = this._subdivisionsY;
  42509. for (var row = 0; row < subdivisionsY; row++) {
  42510. for (var col = 0; col < subdivisionsX; col++) {
  42511. i = col * 3;
  42512. j = row * (subdivisionsX + 1) * 3;
  42513. k = (row + 1) * (subdivisionsX + 1) * 3;
  42514. v1.x = positions[j + i];
  42515. v1.y = positions[j + i + 1];
  42516. v1.z = positions[j + i + 2];
  42517. v2.x = positions[j + i + 3];
  42518. v2.y = positions[j + i + 4];
  42519. v2.z = positions[j + i + 5];
  42520. v3.x = positions[k + i];
  42521. v3.y = positions[k + i + 1];
  42522. v3.z = positions[k + i + 2];
  42523. v4.x = positions[k + i + 3];
  42524. v4.y = positions[k + i + 4];
  42525. v4.z = positions[k + i + 5];
  42526. // 2D slope V1V4
  42527. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42528. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42529. // facet equations :
  42530. // we compute each facet normal vector
  42531. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42532. // we compute the value d by applying the equation to v1 which belongs to the plane
  42533. // then we store the facet equation in a Vector4
  42534. v2.subtractToRef(v1, v1v2);
  42535. v3.subtractToRef(v1, v1v3);
  42536. v4.subtractToRef(v1, v1v4);
  42537. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42538. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42539. norm1.normalize();
  42540. norm2.normalize();
  42541. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42542. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42543. var quad = this._heightQuads[row * subdivisionsX + col];
  42544. quad.slope.copyFromFloats(cd, h);
  42545. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42546. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42547. }
  42548. }
  42549. return this;
  42550. };
  42551. GroundMesh.prototype.serialize = function (serializationObject) {
  42552. _super.prototype.serialize.call(this, serializationObject);
  42553. serializationObject.subdivisionsX = this._subdivisionsX;
  42554. serializationObject.subdivisionsY = this._subdivisionsY;
  42555. serializationObject.minX = this._minX;
  42556. serializationObject.maxX = this._maxX;
  42557. serializationObject.minZ = this._minZ;
  42558. serializationObject.maxZ = this._maxZ;
  42559. serializationObject.width = this._width;
  42560. serializationObject.height = this._height;
  42561. };
  42562. GroundMesh.Parse = function (parsedMesh, scene) {
  42563. var result = new GroundMesh(parsedMesh.name, scene);
  42564. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42565. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42566. result._minX = parsedMesh.minX;
  42567. result._maxX = parsedMesh.maxX;
  42568. result._minZ = parsedMesh.minZ;
  42569. result._maxZ = parsedMesh.maxZ;
  42570. result._width = parsedMesh.width;
  42571. result._height = parsedMesh.height;
  42572. return result;
  42573. };
  42574. return GroundMesh;
  42575. }(BABYLON.Mesh));
  42576. BABYLON.GroundMesh = GroundMesh;
  42577. })(BABYLON || (BABYLON = {}));
  42578. //# sourceMappingURL=babylon.groundMesh.js.map
  42579. var BABYLON;
  42580. (function (BABYLON) {
  42581. /**
  42582. * Creates an instance based on a source mesh.
  42583. */
  42584. var InstancedMesh = (function (_super) {
  42585. __extends(InstancedMesh, _super);
  42586. function InstancedMesh(name, source) {
  42587. var _this = _super.call(this, name, source.getScene()) || this;
  42588. source.instances.push(_this);
  42589. _this._sourceMesh = source;
  42590. _this.position.copyFrom(source.position);
  42591. _this.rotation.copyFrom(source.rotation);
  42592. _this.scaling.copyFrom(source.scaling);
  42593. if (source.rotationQuaternion) {
  42594. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42595. }
  42596. _this.infiniteDistance = source.infiniteDistance;
  42597. _this.setPivotMatrix(source.getPivotMatrix());
  42598. _this.refreshBoundingInfo();
  42599. _this._syncSubMeshes();
  42600. return _this;
  42601. }
  42602. /**
  42603. * Returns the string "InstancedMesh".
  42604. */
  42605. InstancedMesh.prototype.getClassName = function () {
  42606. return "InstancedMesh";
  42607. };
  42608. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42609. // Methods
  42610. get: function () {
  42611. return this._sourceMesh.receiveShadows;
  42612. },
  42613. enumerable: true,
  42614. configurable: true
  42615. });
  42616. Object.defineProperty(InstancedMesh.prototype, "material", {
  42617. get: function () {
  42618. return this._sourceMesh.material;
  42619. },
  42620. enumerable: true,
  42621. configurable: true
  42622. });
  42623. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42624. get: function () {
  42625. return this._sourceMesh.visibility;
  42626. },
  42627. enumerable: true,
  42628. configurable: true
  42629. });
  42630. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42631. get: function () {
  42632. return this._sourceMesh.skeleton;
  42633. },
  42634. enumerable: true,
  42635. configurable: true
  42636. });
  42637. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42638. get: function () {
  42639. return this._sourceMesh.renderingGroupId;
  42640. },
  42641. enumerable: true,
  42642. configurable: true
  42643. });
  42644. /**
  42645. * Returns the total number of vertices (integer).
  42646. */
  42647. InstancedMesh.prototype.getTotalVertices = function () {
  42648. return this._sourceMesh.getTotalVertices();
  42649. };
  42650. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42651. get: function () {
  42652. return this._sourceMesh;
  42653. },
  42654. enumerable: true,
  42655. configurable: true
  42656. });
  42657. /**
  42658. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42659. */
  42660. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42661. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42662. };
  42663. /**
  42664. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42665. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42666. * The `data` are either a numeric array either a Float32Array.
  42667. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42668. * 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).
  42669. * Note that a new underlying VertexBuffer object is created each call.
  42670. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42671. *
  42672. * Possible `kind` values :
  42673. * - BABYLON.VertexBuffer.PositionKind
  42674. * - BABYLON.VertexBuffer.UVKind
  42675. * - BABYLON.VertexBuffer.UV2Kind
  42676. * - BABYLON.VertexBuffer.UV3Kind
  42677. * - BABYLON.VertexBuffer.UV4Kind
  42678. * - BABYLON.VertexBuffer.UV5Kind
  42679. * - BABYLON.VertexBuffer.UV6Kind
  42680. * - BABYLON.VertexBuffer.ColorKind
  42681. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42682. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42683. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42684. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42685. *
  42686. * Returns the Mesh.
  42687. */
  42688. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42689. if (this.sourceMesh) {
  42690. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42691. }
  42692. return this.sourceMesh;
  42693. };
  42694. /**
  42695. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42696. * If the mesh has no geometry, it is simply returned as it is.
  42697. * The `data` are either a numeric array either a Float32Array.
  42698. * No new underlying VertexBuffer object is created.
  42699. * 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.
  42700. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42701. *
  42702. * Possible `kind` values :
  42703. * - BABYLON.VertexBuffer.PositionKind
  42704. * - BABYLON.VertexBuffer.UVKind
  42705. * - BABYLON.VertexBuffer.UV2Kind
  42706. * - BABYLON.VertexBuffer.UV3Kind
  42707. * - BABYLON.VertexBuffer.UV4Kind
  42708. * - BABYLON.VertexBuffer.UV5Kind
  42709. * - BABYLON.VertexBuffer.UV6Kind
  42710. * - BABYLON.VertexBuffer.ColorKind
  42711. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42712. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42713. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42714. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42715. *
  42716. * Returns the Mesh.
  42717. */
  42718. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42719. if (this.sourceMesh) {
  42720. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42721. }
  42722. return this.sourceMesh;
  42723. };
  42724. /**
  42725. * Sets the mesh indices.
  42726. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42727. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42728. * This method creates a new index buffer each call.
  42729. * Returns the Mesh.
  42730. */
  42731. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42732. if (this.sourceMesh) {
  42733. this.sourceMesh.setIndices(indices, totalVertices);
  42734. }
  42735. return this.sourceMesh;
  42736. };
  42737. /**
  42738. * Boolean : True if the mesh owns the requested kind of data.
  42739. */
  42740. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42741. return this._sourceMesh.isVerticesDataPresent(kind);
  42742. };
  42743. /**
  42744. * Returns an array of indices (IndicesArray).
  42745. */
  42746. InstancedMesh.prototype.getIndices = function () {
  42747. return this._sourceMesh.getIndices();
  42748. };
  42749. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42750. get: function () {
  42751. return this._sourceMesh._positions;
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. /**
  42757. * Sets a new updated BoundingInfo to the mesh.
  42758. * Returns the mesh.
  42759. */
  42760. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42761. var meshBB = this._sourceMesh.getBoundingInfo();
  42762. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42763. this._updateBoundingInfo();
  42764. return this;
  42765. };
  42766. InstancedMesh.prototype._preActivate = function () {
  42767. if (this._currentLOD) {
  42768. this._currentLOD._preActivate();
  42769. }
  42770. return this;
  42771. };
  42772. InstancedMesh.prototype._activate = function (renderId) {
  42773. if (this._currentLOD) {
  42774. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42775. }
  42776. return this;
  42777. };
  42778. /**
  42779. * Returns the current associated LOD AbstractMesh.
  42780. */
  42781. InstancedMesh.prototype.getLOD = function (camera) {
  42782. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42783. if (this._currentLOD === this.sourceMesh) {
  42784. return this;
  42785. }
  42786. return this._currentLOD;
  42787. };
  42788. InstancedMesh.prototype._syncSubMeshes = function () {
  42789. this.releaseSubMeshes();
  42790. if (this._sourceMesh.subMeshes) {
  42791. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42792. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42793. }
  42794. }
  42795. return this;
  42796. };
  42797. InstancedMesh.prototype._generatePointsArray = function () {
  42798. return this._sourceMesh._generatePointsArray();
  42799. };
  42800. /**
  42801. * Creates a new InstancedMesh from the current mesh.
  42802. * - name (string) : the cloned mesh name
  42803. * - newParent (optional Node) : the optional Node to parent the clone to.
  42804. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  42805. *
  42806. * Returns the clone.
  42807. */
  42808. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42809. var result = this._sourceMesh.createInstance(name);
  42810. // Deep copy
  42811. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  42812. // Bounding info
  42813. this.refreshBoundingInfo();
  42814. // Parent
  42815. if (newParent) {
  42816. result.parent = newParent;
  42817. }
  42818. if (!doNotCloneChildren) {
  42819. // Children
  42820. for (var index = 0; index < this.getScene().meshes.length; index++) {
  42821. var mesh = this.getScene().meshes[index];
  42822. if (mesh.parent === this) {
  42823. mesh.clone(mesh.name, result);
  42824. }
  42825. }
  42826. }
  42827. result.computeWorldMatrix(true);
  42828. return result;
  42829. };
  42830. /**
  42831. * Disposes the InstancedMesh.
  42832. * Returns nothing.
  42833. */
  42834. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  42835. // Remove from mesh
  42836. var index = this._sourceMesh.instances.indexOf(this);
  42837. this._sourceMesh.instances.splice(index, 1);
  42838. _super.prototype.dispose.call(this, doNotRecurse);
  42839. };
  42840. return InstancedMesh;
  42841. }(BABYLON.AbstractMesh));
  42842. BABYLON.InstancedMesh = InstancedMesh;
  42843. })(BABYLON || (BABYLON = {}));
  42844. //# sourceMappingURL=babylon.instancedMesh.js.map
  42845. /// <reference path="babylon.mesh.ts" />
  42846. var BABYLON;
  42847. (function (BABYLON) {
  42848. var LinesMesh = (function (_super) {
  42849. __extends(LinesMesh, _super);
  42850. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  42851. if (parent === void 0) { parent = null; }
  42852. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42853. _this.useVertexColor = useVertexColor;
  42854. _this.color = new BABYLON.Color3(1, 1, 1);
  42855. _this.alpha = 1;
  42856. if (source) {
  42857. _this.color = source.color.clone();
  42858. _this.alpha = source.alpha;
  42859. _this.useVertexColor = source.useVertexColor;
  42860. }
  42861. _this._intersectionThreshold = 0.1;
  42862. var options = {
  42863. attributes: [BABYLON.VertexBuffer.PositionKind],
  42864. uniforms: ["world", "viewProjection"],
  42865. needAlphaBlending: false,
  42866. };
  42867. if (!useVertexColor) {
  42868. options.uniforms.push("color");
  42869. options.needAlphaBlending = true;
  42870. }
  42871. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  42872. return _this;
  42873. }
  42874. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42875. /**
  42876. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42877. * This margin is expressed in world space coordinates, so its value may vary.
  42878. * Default value is 0.1
  42879. * @returns the intersection Threshold value.
  42880. */
  42881. get: function () {
  42882. return this._intersectionThreshold;
  42883. },
  42884. /**
  42885. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42886. * This margin is expressed in world space coordinates, so its value may vary.
  42887. * @param value the new threshold to apply
  42888. */
  42889. set: function (value) {
  42890. if (this._intersectionThreshold === value) {
  42891. return;
  42892. }
  42893. this._intersectionThreshold = value;
  42894. if (this.geometry) {
  42895. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42896. }
  42897. },
  42898. enumerable: true,
  42899. configurable: true
  42900. });
  42901. /**
  42902. * Returns the string "LineMesh"
  42903. */
  42904. LinesMesh.prototype.getClassName = function () {
  42905. return "LinesMesh";
  42906. };
  42907. Object.defineProperty(LinesMesh.prototype, "material", {
  42908. get: function () {
  42909. return this._colorShader;
  42910. },
  42911. enumerable: true,
  42912. configurable: true
  42913. });
  42914. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42915. get: function () {
  42916. return false;
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. LinesMesh.prototype.createInstance = function (name) {
  42922. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42923. return null;
  42924. };
  42925. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42926. // VBOs
  42927. this._geometry._bind(this._colorShader.getEffect());
  42928. // Color
  42929. if (!this.useVertexColor) {
  42930. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42931. }
  42932. return this;
  42933. };
  42934. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42935. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42936. return this;
  42937. }
  42938. var engine = this.getScene().getEngine();
  42939. // Draw order
  42940. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42941. return this;
  42942. };
  42943. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42944. this._colorShader.dispose();
  42945. _super.prototype.dispose.call(this, doNotRecurse);
  42946. };
  42947. /**
  42948. * Returns a new LineMesh object cloned from the current one.
  42949. */
  42950. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42951. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42952. };
  42953. return LinesMesh;
  42954. }(BABYLON.Mesh));
  42955. BABYLON.LinesMesh = LinesMesh;
  42956. })(BABYLON || (BABYLON = {}));
  42957. //# sourceMappingURL=babylon.linesMesh.js.map
  42958. var BABYLON;
  42959. (function (BABYLON) {
  42960. var ShaderMaterial = (function (_super) {
  42961. __extends(ShaderMaterial, _super);
  42962. function ShaderMaterial(name, scene, shaderPath, options) {
  42963. var _this = _super.call(this, name, scene) || this;
  42964. _this._textures = {};
  42965. _this._textureArrays = {};
  42966. _this._floats = {};
  42967. _this._floatsArrays = {};
  42968. _this._colors3 = {};
  42969. _this._colors3Arrays = {};
  42970. _this._colors4 = {};
  42971. _this._vectors2 = {};
  42972. _this._vectors3 = {};
  42973. _this._vectors4 = {};
  42974. _this._matrices = {};
  42975. _this._matrices3x3 = {};
  42976. _this._matrices2x2 = {};
  42977. _this._vectors3Arrays = {};
  42978. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  42979. _this._shaderPath = shaderPath;
  42980. options.needAlphaBlending = options.needAlphaBlending || false;
  42981. options.needAlphaTesting = options.needAlphaTesting || false;
  42982. options.attributes = options.attributes || ["position", "normal", "uv"];
  42983. options.uniforms = options.uniforms || ["worldViewProjection"];
  42984. options.uniformBuffers = options.uniformBuffers || [];
  42985. options.samplers = options.samplers || [];
  42986. options.defines = options.defines || [];
  42987. _this._options = options;
  42988. return _this;
  42989. }
  42990. ShaderMaterial.prototype.getClassName = function () {
  42991. return "ShaderMaterial";
  42992. };
  42993. ShaderMaterial.prototype.needAlphaBlending = function () {
  42994. return this._options.needAlphaBlending;
  42995. };
  42996. ShaderMaterial.prototype.needAlphaTesting = function () {
  42997. return this._options.needAlphaTesting;
  42998. };
  42999. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43000. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43001. this._options.uniforms.push(uniformName);
  43002. }
  43003. };
  43004. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43005. if (this._options.samplers.indexOf(name) === -1) {
  43006. this._options.samplers.push(name);
  43007. }
  43008. this._textures[name] = texture;
  43009. return this;
  43010. };
  43011. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43012. if (this._options.samplers.indexOf(name) === -1) {
  43013. this._options.samplers.push(name);
  43014. }
  43015. this._checkUniform(name);
  43016. this._textureArrays[name] = textures;
  43017. return this;
  43018. };
  43019. ShaderMaterial.prototype.setFloat = function (name, value) {
  43020. this._checkUniform(name);
  43021. this._floats[name] = value;
  43022. return this;
  43023. };
  43024. ShaderMaterial.prototype.setFloats = function (name, value) {
  43025. this._checkUniform(name);
  43026. this._floatsArrays[name] = value;
  43027. return this;
  43028. };
  43029. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43030. this._checkUniform(name);
  43031. this._colors3[name] = value;
  43032. return this;
  43033. };
  43034. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  43035. this._checkUniform(name);
  43036. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  43037. color.toArray(arr, arr.length);
  43038. return arr;
  43039. }, []);
  43040. return this;
  43041. };
  43042. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43043. this._checkUniform(name);
  43044. this._colors4[name] = value;
  43045. return this;
  43046. };
  43047. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43048. this._checkUniform(name);
  43049. this._vectors2[name] = value;
  43050. return this;
  43051. };
  43052. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43053. this._checkUniform(name);
  43054. this._vectors3[name] = value;
  43055. return this;
  43056. };
  43057. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43058. this._checkUniform(name);
  43059. this._vectors4[name] = value;
  43060. return this;
  43061. };
  43062. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43063. this._checkUniform(name);
  43064. this._matrices[name] = value;
  43065. return this;
  43066. };
  43067. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43068. this._checkUniform(name);
  43069. this._matrices3x3[name] = value;
  43070. return this;
  43071. };
  43072. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43073. this._checkUniform(name);
  43074. this._matrices2x2[name] = value;
  43075. return this;
  43076. };
  43077. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43078. this._checkUniform(name);
  43079. this._vectors3Arrays[name] = value;
  43080. return this;
  43081. };
  43082. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43083. if (!mesh) {
  43084. return true;
  43085. }
  43086. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43087. return false;
  43088. }
  43089. return false;
  43090. };
  43091. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43092. var scene = this.getScene();
  43093. var engine = scene.getEngine();
  43094. if (!this.checkReadyOnEveryCall) {
  43095. if (this._renderId === scene.getRenderId()) {
  43096. if (this._checkCache(scene, mesh, useInstances)) {
  43097. return true;
  43098. }
  43099. }
  43100. }
  43101. // Instances
  43102. var defines = [];
  43103. var attribs = [];
  43104. var fallbacks = new BABYLON.EffectFallbacks();
  43105. if (useInstances) {
  43106. defines.push("#define INSTANCES");
  43107. }
  43108. for (var index = 0; index < this._options.defines.length; index++) {
  43109. defines.push(this._options.defines[index]);
  43110. }
  43111. for (var index = 0; index < this._options.attributes.length; index++) {
  43112. attribs.push(this._options.attributes[index]);
  43113. }
  43114. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  43115. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43116. defines.push("#define VERTEXCOLOR");
  43117. }
  43118. // Bones
  43119. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43120. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43121. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43122. if (mesh.numBoneInfluencers > 4) {
  43123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43125. }
  43126. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43127. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43128. fallbacks.addCPUSkinningFallback(0, mesh);
  43129. if (this._options.uniforms.indexOf("mBones") === -1) {
  43130. this._options.uniforms.push("mBones");
  43131. }
  43132. }
  43133. else {
  43134. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43135. }
  43136. // Textures
  43137. for (var name in this._textures) {
  43138. if (!this._textures[name].isReady()) {
  43139. return false;
  43140. }
  43141. }
  43142. // Alpha test
  43143. if (engine.getAlphaTesting()) {
  43144. defines.push("#define ALPHATEST");
  43145. }
  43146. var previousEffect = this._effect;
  43147. var join = defines.join("\n");
  43148. this._effect = engine.createEffect(this._shaderPath, {
  43149. attributes: attribs,
  43150. uniformsNames: this._options.uniforms,
  43151. uniformBuffersNames: this._options.uniformBuffers,
  43152. samplers: this._options.samplers,
  43153. defines: join,
  43154. fallbacks: fallbacks,
  43155. onCompiled: this.onCompiled,
  43156. onError: this.onError
  43157. }, engine);
  43158. if (!this._effect.isReady()) {
  43159. return false;
  43160. }
  43161. if (previousEffect !== this._effect) {
  43162. scene.resetCachedMaterial();
  43163. }
  43164. this._renderId = scene.getRenderId();
  43165. return true;
  43166. };
  43167. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43168. var scene = this.getScene();
  43169. if (this._options.uniforms.indexOf("world") !== -1) {
  43170. this._effect.setMatrix("world", world);
  43171. }
  43172. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43173. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43174. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43175. }
  43176. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43177. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43178. }
  43179. };
  43180. ShaderMaterial.prototype.bind = function (world, mesh) {
  43181. // Std values
  43182. this.bindOnlyWorldMatrix(world);
  43183. if (this.getScene().getCachedMaterial() !== this) {
  43184. if (this._options.uniforms.indexOf("view") !== -1) {
  43185. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43186. }
  43187. if (this._options.uniforms.indexOf("projection") !== -1) {
  43188. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43189. }
  43190. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43191. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43192. }
  43193. // Bones
  43194. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43195. var name;
  43196. // Texture
  43197. for (name in this._textures) {
  43198. this._effect.setTexture(name, this._textures[name]);
  43199. }
  43200. // Texture arrays
  43201. for (name in this._textureArrays) {
  43202. this._effect.setTextureArray(name, this._textureArrays[name]);
  43203. }
  43204. // Float
  43205. for (name in this._floats) {
  43206. this._effect.setFloat(name, this._floats[name]);
  43207. }
  43208. // Float s
  43209. for (name in this._floatsArrays) {
  43210. this._effect.setArray(name, this._floatsArrays[name]);
  43211. }
  43212. // Color3
  43213. for (name in this._colors3) {
  43214. this._effect.setColor3(name, this._colors3[name]);
  43215. }
  43216. for (name in this._colors3Arrays) {
  43217. this._effect.setArray3(name, this._colors3Arrays[name]);
  43218. }
  43219. // Color4
  43220. for (name in this._colors4) {
  43221. var color = this._colors4[name];
  43222. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43223. }
  43224. // Vector2
  43225. for (name in this._vectors2) {
  43226. this._effect.setVector2(name, this._vectors2[name]);
  43227. }
  43228. // Vector3
  43229. for (name in this._vectors3) {
  43230. this._effect.setVector3(name, this._vectors3[name]);
  43231. }
  43232. // Vector4
  43233. for (name in this._vectors4) {
  43234. this._effect.setVector4(name, this._vectors4[name]);
  43235. }
  43236. // Matrix
  43237. for (name in this._matrices) {
  43238. this._effect.setMatrix(name, this._matrices[name]);
  43239. }
  43240. // Matrix 3x3
  43241. for (name in this._matrices3x3) {
  43242. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43243. }
  43244. // Matrix 2x2
  43245. for (name in this._matrices2x2) {
  43246. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43247. }
  43248. // Vector3Array
  43249. for (name in this._vectors3Arrays) {
  43250. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43251. }
  43252. }
  43253. this._afterBind(mesh);
  43254. };
  43255. ShaderMaterial.prototype.getActiveTextures = function () {
  43256. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43257. for (var name in this._textures) {
  43258. activeTextures.push(this._textures[name]);
  43259. }
  43260. for (var name in this._textureArrays) {
  43261. var array = this._textureArrays[name];
  43262. for (var index = 0; index < array.length; index++) {
  43263. activeTextures.push(array[index]);
  43264. }
  43265. }
  43266. return activeTextures;
  43267. };
  43268. ShaderMaterial.prototype.hasTexture = function (texture) {
  43269. if (_super.prototype.hasTexture.call(this, texture)) {
  43270. return true;
  43271. }
  43272. for (var name in this._textures) {
  43273. if (this._textures[name] === texture) {
  43274. return true;
  43275. }
  43276. }
  43277. for (var name in this._textureArrays) {
  43278. var array = this._textureArrays[name];
  43279. for (var index = 0; index < array.length; index++) {
  43280. if (array[index] === texture) {
  43281. return true;
  43282. }
  43283. }
  43284. }
  43285. return false;
  43286. };
  43287. ShaderMaterial.prototype.clone = function (name) {
  43288. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43289. return newShaderMaterial;
  43290. };
  43291. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43292. if (forceDisposeTextures) {
  43293. var name;
  43294. for (name in this._textures) {
  43295. this._textures[name].dispose();
  43296. }
  43297. for (name in this._textureArrays) {
  43298. var array = this._textureArrays[name];
  43299. for (var index = 0; index < array.length; index++) {
  43300. array[index].dispose();
  43301. }
  43302. }
  43303. }
  43304. this._textures = {};
  43305. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43306. };
  43307. ShaderMaterial.prototype.serialize = function () {
  43308. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43309. serializationObject.customType = "BABYLON.ShaderMaterial";
  43310. serializationObject.options = this._options;
  43311. serializationObject.shaderPath = this._shaderPath;
  43312. var name;
  43313. // Texture
  43314. serializationObject.textures = {};
  43315. for (name in this._textures) {
  43316. serializationObject.textures[name] = this._textures[name].serialize();
  43317. }
  43318. // Texture arrays
  43319. serializationObject.textureArrays = {};
  43320. for (name in this._textureArrays) {
  43321. serializationObject.textureArrays[name] = [];
  43322. var array = this._textureArrays[name];
  43323. for (var index = 0; index < array.length; index++) {
  43324. serializationObject.textureArrays[name].push(array[index].serialize());
  43325. }
  43326. }
  43327. // Float
  43328. serializationObject.floats = {};
  43329. for (name in this._floats) {
  43330. serializationObject.floats[name] = this._floats[name];
  43331. }
  43332. // Float s
  43333. serializationObject.floatArrays = {};
  43334. for (name in this._floatsArrays) {
  43335. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43336. }
  43337. // Color3
  43338. serializationObject.colors3 = {};
  43339. for (name in this._colors3) {
  43340. serializationObject.colors3[name] = this._colors3[name].asArray();
  43341. }
  43342. // Color3 array
  43343. serializationObject.colors3Arrays = {};
  43344. for (name in this._colors3Arrays) {
  43345. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43346. }
  43347. // Color4
  43348. serializationObject.colors4 = {};
  43349. for (name in this._colors4) {
  43350. serializationObject.colors4[name] = this._colors4[name].asArray();
  43351. }
  43352. // Vector2
  43353. serializationObject.vectors2 = {};
  43354. for (name in this._vectors2) {
  43355. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43356. }
  43357. // Vector3
  43358. serializationObject.vectors3 = {};
  43359. for (name in this._vectors3) {
  43360. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43361. }
  43362. // Vector4
  43363. serializationObject.vectors4 = {};
  43364. for (name in this._vectors4) {
  43365. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43366. }
  43367. // Matrix
  43368. serializationObject.matrices = {};
  43369. for (name in this._matrices) {
  43370. serializationObject.matrices[name] = this._matrices[name].asArray();
  43371. }
  43372. // Matrix 3x3
  43373. serializationObject.matrices3x3 = {};
  43374. for (name in this._matrices3x3) {
  43375. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43376. }
  43377. // Matrix 2x2
  43378. serializationObject.matrices2x2 = {};
  43379. for (name in this._matrices2x2) {
  43380. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43381. }
  43382. // Vector3Array
  43383. serializationObject.vectors3Arrays = {};
  43384. for (name in this._vectors3Arrays) {
  43385. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43386. }
  43387. return serializationObject;
  43388. };
  43389. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43390. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43391. var name;
  43392. // Texture
  43393. for (name in source.textures) {
  43394. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43395. }
  43396. // Texture arrays
  43397. for (name in source.textureArrays) {
  43398. var array = source.textureArrays[name];
  43399. var textureArray = new Array();
  43400. for (var index = 0; index < array.length; index++) {
  43401. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43402. }
  43403. material.setTextureArray(name, textureArray);
  43404. }
  43405. // Float
  43406. for (name in source.floats) {
  43407. material.setFloat(name, source.floats[name]);
  43408. }
  43409. // Float s
  43410. for (name in source.floatsArrays) {
  43411. material.setFloats(name, source.floatsArrays[name]);
  43412. }
  43413. // Color3
  43414. for (name in source.colors3) {
  43415. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43416. }
  43417. // Color3 arrays
  43418. for (name in source.colors3Arrays) {
  43419. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43420. if (i % 3 === 0) {
  43421. arr.push([num]);
  43422. }
  43423. else {
  43424. arr[arr.length - 1].push(num);
  43425. }
  43426. return arr;
  43427. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43428. material.setColor3Array(name, colors);
  43429. }
  43430. // Color4
  43431. for (name in source.colors4) {
  43432. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43433. }
  43434. // Vector2
  43435. for (name in source.vectors2) {
  43436. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43437. }
  43438. // Vector3
  43439. for (name in source.vectors3) {
  43440. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43441. }
  43442. // Vector4
  43443. for (name in source.vectors4) {
  43444. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43445. }
  43446. // Matrix
  43447. for (name in source.matrices) {
  43448. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43449. }
  43450. // Matrix 3x3
  43451. for (name in source.matrices3x3) {
  43452. material.setMatrix3x3(name, source.matrices3x3[name]);
  43453. }
  43454. // Matrix 2x2
  43455. for (name in source.matrices2x2) {
  43456. material.setMatrix2x2(name, source.matrices2x2[name]);
  43457. }
  43458. // Vector3Array
  43459. for (name in source.vectors3Arrays) {
  43460. material.setArray3(name, source.vectors3Arrays[name]);
  43461. }
  43462. return material;
  43463. };
  43464. return ShaderMaterial;
  43465. }(BABYLON.Material));
  43466. BABYLON.ShaderMaterial = ShaderMaterial;
  43467. })(BABYLON || (BABYLON = {}));
  43468. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43469. var BABYLON;
  43470. (function (BABYLON) {
  43471. var MeshBuilder = (function () {
  43472. function MeshBuilder() {
  43473. }
  43474. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43475. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43476. return BABYLON.Mesh.DOUBLESIDE;
  43477. }
  43478. if (orientation === undefined || orientation === null) {
  43479. return BABYLON.Mesh.FRONTSIDE;
  43480. }
  43481. return orientation;
  43482. };
  43483. /**
  43484. * Creates a box mesh.
  43485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43486. * The parameter `size` sets the size (float) of each box side (default 1).
  43487. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43488. * 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).
  43489. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43491. * 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).
  43492. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43494. */
  43495. MeshBuilder.CreateBox = function (name, options, scene) {
  43496. var box = new BABYLON.Mesh(name, scene);
  43497. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43498. box.sideOrientation = options.sideOrientation;
  43499. var vertexData = BABYLON.VertexData.CreateBox(options);
  43500. vertexData.applyToMesh(box, options.updatable);
  43501. return box;
  43502. };
  43503. /**
  43504. * Creates a sphere mesh.
  43505. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43506. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43507. * 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`).
  43508. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43509. * 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
  43510. * 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).
  43511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43512. * 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).
  43513. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43515. */
  43516. MeshBuilder.CreateSphere = function (name, options, scene) {
  43517. var sphere = new BABYLON.Mesh(name, scene);
  43518. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43519. sphere.sideOrientation = options.sideOrientation;
  43520. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43521. vertexData.applyToMesh(sphere, options.updatable);
  43522. return sphere;
  43523. };
  43524. /**
  43525. * Creates a plane polygonal mesh. By default, this is a disc.
  43526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43527. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43528. * 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.
  43529. * 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
  43530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43531. * 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).
  43532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43534. */
  43535. MeshBuilder.CreateDisc = function (name, options, scene) {
  43536. var disc = new BABYLON.Mesh(name, scene);
  43537. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43538. disc.sideOrientation = options.sideOrientation;
  43539. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43540. vertexData.applyToMesh(disc, options.updatable);
  43541. return disc;
  43542. };
  43543. /**
  43544. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43545. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43546. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43547. * 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`).
  43548. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43549. * 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.
  43550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43551. * 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).
  43552. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43554. */
  43555. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43556. var sphere = new BABYLON.Mesh(name, scene);
  43557. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43558. sphere.sideOrientation = options.sideOrientation;
  43559. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  43560. vertexData.applyToMesh(sphere, options.updatable);
  43561. return sphere;
  43562. };
  43563. ;
  43564. /**
  43565. * Creates a ribbon mesh.
  43566. * 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.
  43567. *
  43568. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  43569. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  43570. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  43571. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  43572. * 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.
  43573. * 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.
  43574. * 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
  43575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43576. * 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).
  43577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43578. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43579. * 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.
  43580. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  43581. * 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
  43582. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  43583. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  43584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43585. */
  43586. MeshBuilder.CreateRibbon = function (name, options, scene) {
  43587. var pathArray = options.pathArray;
  43588. var closeArray = options.closeArray;
  43589. var closePath = options.closePath;
  43590. var offset = options.offset;
  43591. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43592. var instance = options.instance;
  43593. var updatable = options.updatable;
  43594. if (instance) {
  43595. // positionFunction : ribbon case
  43596. // only pathArray and sideOrientation parameters are taken into account for positions update
  43597. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43598. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43599. var positionFunction = function (positions) {
  43600. var minlg = pathArray[0].length;
  43601. var i = 0;
  43602. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43603. for (var si = 1; si <= ns; si++) {
  43604. for (var p = 0; p < pathArray.length; p++) {
  43605. var path = pathArray[p];
  43606. var l = path.length;
  43607. minlg = (minlg < l) ? minlg : l;
  43608. var j = 0;
  43609. while (j < minlg) {
  43610. positions[i] = path[j].x;
  43611. positions[i + 1] = path[j].y;
  43612. positions[i + 2] = path[j].z;
  43613. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43614. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43615. }
  43616. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43617. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43618. }
  43619. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43620. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43621. }
  43622. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43623. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43624. }
  43625. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43626. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43627. }
  43628. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43629. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43630. }
  43631. j++;
  43632. i += 3;
  43633. }
  43634. if (instance._closePath) {
  43635. positions[i] = path[0].x;
  43636. positions[i + 1] = path[0].y;
  43637. positions[i + 2] = path[0].z;
  43638. i += 3;
  43639. }
  43640. }
  43641. }
  43642. };
  43643. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43644. positionFunction(positions);
  43645. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43646. instance._boundingInfo.update(instance._worldMatrix);
  43647. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43648. if (options.colors) {
  43649. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43650. for (var c = 0; c < options.colors.length; c++) {
  43651. colors[c * 4] = options.colors[c].r;
  43652. colors[c * 4 + 1] = options.colors[c].g;
  43653. colors[c * 4 + 2] = options.colors[c].b;
  43654. colors[c * 4 + 3] = options.colors[c].a;
  43655. }
  43656. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43657. }
  43658. if (options.uvs) {
  43659. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43660. for (var i = 0; i < options.uvs.length; i++) {
  43661. uvs[i * 2] = options.uvs[i].x;
  43662. uvs[i * 2 + 1] = options.uvs[i].y;
  43663. }
  43664. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43665. }
  43666. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43667. var indices = instance.getIndices();
  43668. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43669. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43670. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43671. if (instance._closePath) {
  43672. var indexFirst = 0;
  43673. var indexLast = 0;
  43674. for (var p = 0; p < pathArray.length; p++) {
  43675. indexFirst = instance._idx[p] * 3;
  43676. if (p + 1 < pathArray.length) {
  43677. indexLast = (instance._idx[p + 1] - 1) * 3;
  43678. }
  43679. else {
  43680. indexLast = normals.length - 3;
  43681. }
  43682. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43683. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43684. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43685. normals[indexLast] = normals[indexFirst];
  43686. normals[indexLast + 1] = normals[indexFirst + 1];
  43687. normals[indexLast + 2] = normals[indexFirst + 2];
  43688. }
  43689. }
  43690. if (!(instance.areNormalsFrozen)) {
  43691. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43692. }
  43693. }
  43694. return instance;
  43695. }
  43696. else {
  43697. var ribbon = new BABYLON.Mesh(name, scene);
  43698. ribbon.sideOrientation = sideOrientation;
  43699. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43700. if (closePath) {
  43701. ribbon._idx = vertexData._idx;
  43702. }
  43703. ribbon._closePath = closePath;
  43704. ribbon._closeArray = closeArray;
  43705. vertexData.applyToMesh(ribbon, updatable);
  43706. return ribbon;
  43707. }
  43708. };
  43709. /**
  43710. * Creates a cylinder or a cone mesh.
  43711. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43712. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43713. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43714. * 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.
  43715. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43716. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43717. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43718. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43719. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43720. * 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).
  43721. * 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
  43722. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43723. * 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
  43724. * 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.
  43725. * If `enclose` is false, a ring surface is one element.
  43726. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43727. * 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
  43728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43729. * 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).
  43730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43732. */
  43733. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43734. var cylinder = new BABYLON.Mesh(name, scene);
  43735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43736. cylinder.sideOrientation = options.sideOrientation;
  43737. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43738. vertexData.applyToMesh(cylinder, options.updatable);
  43739. return cylinder;
  43740. };
  43741. /**
  43742. * Creates a torus mesh.
  43743. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43744. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43745. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43746. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43748. * 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).
  43749. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43751. */
  43752. MeshBuilder.CreateTorus = function (name, options, scene) {
  43753. var torus = new BABYLON.Mesh(name, scene);
  43754. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43755. torus.sideOrientation = options.sideOrientation;
  43756. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43757. vertexData.applyToMesh(torus, options.updatable);
  43758. return torus;
  43759. };
  43760. /**
  43761. * Creates a torus knot mesh.
  43762. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43763. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43764. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43765. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43766. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43768. * 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).
  43769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43771. */
  43772. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43773. var torusKnot = new BABYLON.Mesh(name, scene);
  43774. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43775. torusKnot.sideOrientation = options.sideOrientation;
  43776. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43777. vertexData.applyToMesh(torusKnot, options.updatable);
  43778. return torusKnot;
  43779. };
  43780. /**
  43781. * Creates a line system mesh.
  43782. * A line system is a pool of many lines gathered in a single mesh.
  43783. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43784. * 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.
  43785. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43786. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43787. * 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
  43788. * 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
  43789. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43791. */
  43792. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43793. var instance = options.instance;
  43794. var lines = options.lines;
  43795. if (instance) {
  43796. var positionFunction = function (positions) {
  43797. var i = 0;
  43798. for (var l = 0; l < lines.length; l++) {
  43799. var points = lines[l];
  43800. for (var p = 0; p < points.length; p++) {
  43801. positions[i] = points[p].x;
  43802. positions[i + 1] = points[p].y;
  43803. positions[i + 2] = points[p].z;
  43804. i += 3;
  43805. }
  43806. }
  43807. };
  43808. instance.updateMeshPositions(positionFunction, false);
  43809. return instance;
  43810. }
  43811. // line system creation
  43812. var lineSystem = new BABYLON.LinesMesh(name, scene);
  43813. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  43814. vertexData.applyToMesh(lineSystem, options.updatable);
  43815. return lineSystem;
  43816. };
  43817. /**
  43818. * Creates a line mesh.
  43819. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  43820. * 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.
  43821. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43822. * The parameter `points` is an array successive Vector3.
  43823. * 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
  43824. * When updating an instance, remember that only point positions can change, not the number of points.
  43825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43826. */
  43827. MeshBuilder.CreateLines = function (name, options, scene) {
  43828. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  43829. return lines;
  43830. };
  43831. /**
  43832. * Creates a dashed line mesh.
  43833. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  43834. * 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.
  43835. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43836. * The parameter `points` is an array successive Vector3.
  43837. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  43838. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  43839. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  43840. * 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
  43841. * When updating an instance, remember that only point positions can change, not the number of points.
  43842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43843. */
  43844. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  43845. var points = options.points;
  43846. var instance = options.instance;
  43847. var gapSize = options.gapSize;
  43848. var dashNb = options.dashNb;
  43849. var dashSize = options.dashSize;
  43850. if (instance) {
  43851. var positionFunction = function (positions) {
  43852. var curvect = BABYLON.Vector3.Zero();
  43853. var nbSeg = positions.length / 6;
  43854. var lg = 0;
  43855. var nb = 0;
  43856. var shft = 0;
  43857. var dashshft = 0;
  43858. var curshft = 0;
  43859. var p = 0;
  43860. var i = 0;
  43861. var j = 0;
  43862. for (i = 0; i < points.length - 1; i++) {
  43863. points[i + 1].subtractToRef(points[i], curvect);
  43864. lg += curvect.length();
  43865. }
  43866. shft = lg / nbSeg;
  43867. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  43868. for (i = 0; i < points.length - 1; i++) {
  43869. points[i + 1].subtractToRef(points[i], curvect);
  43870. nb = Math.floor(curvect.length() / shft);
  43871. curvect.normalize();
  43872. j = 0;
  43873. while (j < nb && p < positions.length) {
  43874. curshft = shft * j;
  43875. positions[p] = points[i].x + curshft * curvect.x;
  43876. positions[p + 1] = points[i].y + curshft * curvect.y;
  43877. positions[p + 2] = points[i].z + curshft * curvect.z;
  43878. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  43879. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  43880. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  43881. p += 6;
  43882. j++;
  43883. }
  43884. }
  43885. while (p < positions.length) {
  43886. positions[p] = points[i].x;
  43887. positions[p + 1] = points[i].y;
  43888. positions[p + 2] = points[i].z;
  43889. p += 3;
  43890. }
  43891. };
  43892. instance.updateMeshPositions(positionFunction, false);
  43893. return instance;
  43894. }
  43895. // dashed lines creation
  43896. var dashedLines = new BABYLON.LinesMesh(name, scene);
  43897. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  43898. vertexData.applyToMesh(dashedLines, options.updatable);
  43899. dashedLines.dashSize = dashSize;
  43900. dashedLines.gapSize = gapSize;
  43901. return dashedLines;
  43902. };
  43903. /**
  43904. * Creates an extruded shape mesh.
  43905. * 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.
  43906. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  43907. *
  43908. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43909. * 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
  43910. * extruded along the Z axis.
  43911. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43912. * 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.
  43913. * The parameter `scale` (float, default 1) is the value to scale the shape.
  43914. * 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
  43915. * 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
  43916. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43918. * 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).
  43919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43920. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43922. */
  43923. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  43924. var path = options.path;
  43925. var shape = options.shape;
  43926. var scale = options.scale || 1;
  43927. var rotation = options.rotation || 0;
  43928. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43929. var updatable = options.updatable;
  43930. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43931. var instance = options.instance;
  43932. var invertUV = options.invertUV || false;
  43933. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43934. };
  43935. /**
  43936. * Creates an custom extruded shape mesh.
  43937. * 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.
  43938. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  43939. *
  43940. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43941. * 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
  43942. * extruded along the Z axis.
  43943. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43944. * 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
  43945. * and the distance of this point from the begining of the path :
  43946. * ```javascript
  43947. * var rotationFunction = function(i, distance) {
  43948. * // do things
  43949. * return rotationValue; }
  43950. * ```
  43951. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  43952. * 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
  43953. * and the distance of this point from the begining of the path :
  43954. * ```javascript
  43955. * var scaleFunction = function(i, distance) {
  43956. * // do things
  43957. * return scaleValue;}
  43958. * ```
  43959. * It must returns a float value that will be the scale value applied to the shape on each path point.
  43960. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  43961. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  43962. * 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
  43963. * 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
  43964. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43966. * 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).
  43967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43968. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43970. */
  43971. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  43972. var path = options.path;
  43973. var shape = options.shape;
  43974. var scaleFunction = options.scaleFunction || (function () { return 1; });
  43975. var rotationFunction = options.rotationFunction || (function () { return 0; });
  43976. var ribbonCloseArray = options.ribbonCloseArray || false;
  43977. var ribbonClosePath = options.ribbonClosePath || false;
  43978. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43979. var updatable = options.updatable;
  43980. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43981. var instance = options.instance;
  43982. var invertUV = options.invertUV || false;
  43983. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43984. };
  43985. /**
  43986. * Creates lathe mesh.
  43987. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  43988. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  43989. *
  43990. * 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
  43991. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  43992. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  43993. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  43994. * 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.
  43995. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  43996. * 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
  43997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43998. * 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).
  43999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44000. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44002. */
  44003. MeshBuilder.CreateLathe = function (name, options, scene) {
  44004. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  44005. var closed = (options.closed === undefined) ? true : options.closed;
  44006. var shape = options.shape;
  44007. var radius = options.radius || 1;
  44008. var tessellation = options.tessellation || 64;
  44009. var updatable = options.updatable;
  44010. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44011. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44012. var pi2 = Math.PI * 2;
  44013. var paths = new Array();
  44014. var invertUV = options.invertUV || false;
  44015. var i = 0;
  44016. var p = 0;
  44017. var step = pi2 / tessellation * arc;
  44018. var rotated;
  44019. var path = new Array();
  44020. ;
  44021. for (i = 0; i <= tessellation; i++) {
  44022. var path = [];
  44023. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  44024. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  44025. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  44026. }
  44027. for (p = 0; p < shape.length; p++) {
  44028. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  44029. path.push(rotated);
  44030. }
  44031. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  44032. 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));
  44033. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  44034. }
  44035. paths.push(path);
  44036. }
  44037. // lathe ribbon
  44038. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44039. return lathe;
  44040. };
  44041. /**
  44042. * Creates a plane mesh.
  44043. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44044. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  44045. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  44046. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  44047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44048. * 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).
  44049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44051. */
  44052. MeshBuilder.CreatePlane = function (name, options, scene) {
  44053. var plane = new BABYLON.Mesh(name, scene);
  44054. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44055. plane.sideOrientation = options.sideOrientation;
  44056. var vertexData = BABYLON.VertexData.CreatePlane(options);
  44057. vertexData.applyToMesh(plane, options.updatable);
  44058. if (options.sourcePlane) {
  44059. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  44060. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  44061. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  44062. plane.rotate(vectorProduct, product);
  44063. }
  44064. return plane;
  44065. };
  44066. /**
  44067. * Creates a ground mesh.
  44068. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44069. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  44070. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  44071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44072. */
  44073. MeshBuilder.CreateGround = function (name, options, scene) {
  44074. var ground = new BABYLON.GroundMesh(name, scene);
  44075. ground._setReady(false);
  44076. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  44077. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  44078. ground._width = options.width || 1;
  44079. ground._height = options.height || 1;
  44080. ground._maxX = ground._width / 2;
  44081. ground._maxZ = ground._height / 2;
  44082. ground._minX = -ground._maxX;
  44083. ground._minZ = -ground._maxZ;
  44084. var vertexData = BABYLON.VertexData.CreateGround(options);
  44085. vertexData.applyToMesh(ground, options.updatable);
  44086. ground._setReady(true);
  44087. return ground;
  44088. };
  44089. /**
  44090. * Creates a tiled ground mesh.
  44091. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  44092. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  44093. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  44094. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  44095. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  44096. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  44097. * numbers of subdivisions on the ground width and height of each tile.
  44098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44099. */
  44100. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  44101. var tiledGround = new BABYLON.Mesh(name, scene);
  44102. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  44103. vertexData.applyToMesh(tiledGround, options.updatable);
  44104. return tiledGround;
  44105. };
  44106. /**
  44107. * Creates a ground mesh from a height map.
  44108. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  44109. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  44110. * The parameter `url` sets the URL of the height map image resource.
  44111. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  44112. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  44113. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  44114. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  44115. * 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.
  44116. * 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).
  44117. * This function is passed the newly built mesh :
  44118. * ```javascript
  44119. * function(mesh) { // do things
  44120. * return; }
  44121. * ```
  44122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44123. */
  44124. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  44125. var width = options.width || 10.0;
  44126. var height = options.height || 10.0;
  44127. var subdivisions = options.subdivisions || 1 | 0;
  44128. var minHeight = options.minHeight || 0.0;
  44129. var maxHeight = options.maxHeight || 1.0;
  44130. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44131. var updatable = options.updatable;
  44132. var onReady = options.onReady;
  44133. var ground = new BABYLON.GroundMesh(name, scene);
  44134. ground._subdivisionsX = subdivisions;
  44135. ground._subdivisionsY = subdivisions;
  44136. ground._width = width;
  44137. ground._height = height;
  44138. ground._maxX = ground._width / 2.0;
  44139. ground._maxZ = ground._height / 2.0;
  44140. ground._minX = -ground._maxX;
  44141. ground._minZ = -ground._maxZ;
  44142. ground._setReady(false);
  44143. var onload = function (img) {
  44144. // Getting height map data
  44145. var canvas = document.createElement("canvas");
  44146. var context = canvas.getContext("2d");
  44147. var bufferWidth = img.width;
  44148. var bufferHeight = img.height;
  44149. canvas.width = bufferWidth;
  44150. canvas.height = bufferHeight;
  44151. context.drawImage(img, 0, 0);
  44152. // Create VertexData from map data
  44153. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44154. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44155. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44156. width: width, height: height,
  44157. subdivisions: subdivisions,
  44158. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44159. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44160. });
  44161. vertexData.applyToMesh(ground, updatable);
  44162. ground._setReady(true);
  44163. //execute ready callback, if set
  44164. if (onReady) {
  44165. onReady(ground);
  44166. }
  44167. };
  44168. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44169. return ground;
  44170. };
  44171. /**
  44172. * Creates a polygon mesh.
  44173. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44174. * 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.
  44175. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44177. * 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).
  44178. * Remember you can only change the shape positions, not their number when updating a polygon.
  44179. */
  44180. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44181. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44182. var shape = options.shape;
  44183. var holes = options.holes || [];
  44184. var depth = options.depth || 0;
  44185. var contours = [];
  44186. var hole = [];
  44187. for (var i = 0; i < shape.length; i++) {
  44188. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44189. }
  44190. var epsilon = 0.00000001;
  44191. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44192. contours.pop();
  44193. }
  44194. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44195. for (var hNb = 0; hNb < holes.length; hNb++) {
  44196. hole = [];
  44197. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44198. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44199. }
  44200. polygonTriangulation.addHole(hole);
  44201. }
  44202. var polygon = polygonTriangulation.build(options.updatable, depth);
  44203. polygon.sideOrientation = options.sideOrientation;
  44204. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44205. vertexData.applyToMesh(polygon, options.updatable);
  44206. return polygon;
  44207. };
  44208. ;
  44209. /**
  44210. * Creates an extruded polygon mesh, with depth in the Y direction.
  44211. * 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).
  44212. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44213. */
  44214. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44215. return MeshBuilder.CreatePolygon(name, options, scene);
  44216. };
  44217. ;
  44218. /**
  44219. * Creates a tube mesh.
  44220. * 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.
  44221. *
  44222. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44223. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44224. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44225. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44226. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44227. * 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.
  44228. * It must return a radius value (positive float) :
  44229. * ```javascript
  44230. * var radiusFunction = function(i, distance) {
  44231. * // do things
  44232. * return radius; }
  44233. * ```
  44234. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44235. * 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
  44236. * 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
  44237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44238. * 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).
  44239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44240. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44242. */
  44243. MeshBuilder.CreateTube = function (name, options, scene) {
  44244. var path = options.path;
  44245. var radius = options.radius || 1.0;
  44246. var tessellation = options.tessellation || 64 | 0;
  44247. var radiusFunction = options.radiusFunction;
  44248. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44249. var invertUV = options.invertUV || false;
  44250. var updatable = options.updatable;
  44251. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44252. var instance = options.instance;
  44253. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44254. // tube geometry
  44255. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44256. var tangents = path3D.getTangents();
  44257. var normals = path3D.getNormals();
  44258. var distances = path3D.getDistances();
  44259. var pi2 = Math.PI * 2;
  44260. var step = pi2 / tessellation * arc;
  44261. var returnRadius = function () { return radius; };
  44262. var radiusFunctionFinal = radiusFunction || returnRadius;
  44263. var circlePath;
  44264. var rad;
  44265. var normal;
  44266. var rotated;
  44267. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44268. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44269. for (var i = 0; i < path.length; i++) {
  44270. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44271. circlePath = Array(); // current circle array
  44272. normal = normals[i]; // current normal
  44273. for (var t = 0; t < tessellation; t++) {
  44274. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44275. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44276. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44277. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44278. circlePath[t] = rotated;
  44279. }
  44280. circlePaths[index] = circlePath;
  44281. index++;
  44282. }
  44283. // cap
  44284. var capPath = function (nbPoints, pathIndex) {
  44285. var pointCap = Array();
  44286. for (var i = 0; i < nbPoints; i++) {
  44287. pointCap.push(path[pathIndex]);
  44288. }
  44289. return pointCap;
  44290. };
  44291. switch (cap) {
  44292. case BABYLON.Mesh.NO_CAP:
  44293. break;
  44294. case BABYLON.Mesh.CAP_START:
  44295. circlePaths[0] = capPath(tessellation, 0);
  44296. circlePaths[1] = circlePaths[2].slice(0);
  44297. break;
  44298. case BABYLON.Mesh.CAP_END:
  44299. circlePaths[index] = circlePaths[index - 1].slice(0);
  44300. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44301. break;
  44302. case BABYLON.Mesh.CAP_ALL:
  44303. circlePaths[0] = capPath(tessellation, 0);
  44304. circlePaths[1] = circlePaths[2].slice(0);
  44305. circlePaths[index] = circlePaths[index - 1].slice(0);
  44306. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44307. break;
  44308. default:
  44309. break;
  44310. }
  44311. return circlePaths;
  44312. };
  44313. var path3D;
  44314. var pathArray;
  44315. if (instance) {
  44316. var arc = options.arc || instance.arc;
  44317. path3D = (instance.path3D).update(path);
  44318. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44319. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44320. instance.path3D = path3D;
  44321. instance.pathArray = pathArray;
  44322. instance.arc = arc;
  44323. return instance;
  44324. }
  44325. // tube creation
  44326. path3D = new BABYLON.Path3D(path);
  44327. var newPathArray = new Array();
  44328. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44329. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44330. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44331. tube.pathArray = pathArray;
  44332. tube.path3D = path3D;
  44333. tube.tessellation = tessellation;
  44334. tube.cap = cap;
  44335. tube.arc = options.arc;
  44336. return tube;
  44337. };
  44338. /**
  44339. * Creates a polyhedron mesh.
  44340. *
  44341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44342. * 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
  44343. * to choose the wanted type.
  44344. * The parameter `size` (positive float, default 1) sets the polygon size.
  44345. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44346. * 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`.
  44347. * 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
  44348. * 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)`).
  44349. * 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
  44350. * 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.
  44351. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44352. * 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).
  44353. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44355. */
  44356. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44357. var polyhedron = new BABYLON.Mesh(name, scene);
  44358. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44359. polyhedron.sideOrientation = options.sideOrientation;
  44360. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44361. vertexData.applyToMesh(polyhedron, options.updatable);
  44362. return polyhedron;
  44363. };
  44364. /**
  44365. * Creates a decal mesh.
  44366. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44367. * 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.
  44368. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44369. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44370. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44371. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44372. */
  44373. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44374. var indices = sourceMesh.getIndices();
  44375. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44376. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44377. var position = options.position || BABYLON.Vector3.Zero();
  44378. var normal = options.normal || BABYLON.Vector3.Up();
  44379. var size = options.size || BABYLON.Vector3.One();
  44380. var angle = options.angle || 0;
  44381. // Getting correct rotation
  44382. if (!normal) {
  44383. var target = new BABYLON.Vector3(0, 0, 1);
  44384. var camera = sourceMesh.getScene().activeCamera;
  44385. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44386. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44387. }
  44388. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44389. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44390. var pitch = Math.atan2(normal.y, len);
  44391. // Matrix
  44392. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44393. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44394. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44395. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44396. var vertexData = new BABYLON.VertexData();
  44397. vertexData.indices = [];
  44398. vertexData.positions = [];
  44399. vertexData.normals = [];
  44400. vertexData.uvs = [];
  44401. var currentVertexDataIndex = 0;
  44402. var extractDecalVector3 = function (indexId) {
  44403. var vertexId = indices[indexId];
  44404. var result = new BABYLON.PositionNormalVertex();
  44405. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44406. // Send vector to decal local world
  44407. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44408. // Get normal
  44409. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44410. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44411. return result;
  44412. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44413. var clip = function (vertices, axis) {
  44414. if (vertices.length === 0) {
  44415. return vertices;
  44416. }
  44417. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44418. var clipVertices = function (v0, v1) {
  44419. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44420. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44421. };
  44422. var result = new Array();
  44423. for (var index = 0; index < vertices.length; index += 3) {
  44424. var v1Out;
  44425. var v2Out;
  44426. var v3Out;
  44427. var total = 0;
  44428. var nV1, nV2, nV3, nV4;
  44429. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44430. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44431. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44432. v1Out = d1 > 0;
  44433. v2Out = d2 > 0;
  44434. v3Out = d3 > 0;
  44435. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44436. switch (total) {
  44437. case 0:
  44438. result.push(vertices[index]);
  44439. result.push(vertices[index + 1]);
  44440. result.push(vertices[index + 2]);
  44441. break;
  44442. case 1:
  44443. if (v1Out) {
  44444. nV1 = vertices[index + 1];
  44445. nV2 = vertices[index + 2];
  44446. nV3 = clipVertices(vertices[index], nV1);
  44447. nV4 = clipVertices(vertices[index], nV2);
  44448. }
  44449. if (v2Out) {
  44450. nV1 = vertices[index];
  44451. nV2 = vertices[index + 2];
  44452. nV3 = clipVertices(vertices[index + 1], nV1);
  44453. nV4 = clipVertices(vertices[index + 1], nV2);
  44454. result.push(nV3);
  44455. result.push(nV2.clone());
  44456. result.push(nV1.clone());
  44457. result.push(nV2.clone());
  44458. result.push(nV3.clone());
  44459. result.push(nV4);
  44460. break;
  44461. }
  44462. if (v3Out) {
  44463. nV1 = vertices[index];
  44464. nV2 = vertices[index + 1];
  44465. nV3 = clipVertices(vertices[index + 2], nV1);
  44466. nV4 = clipVertices(vertices[index + 2], nV2);
  44467. }
  44468. result.push(nV1.clone());
  44469. result.push(nV2.clone());
  44470. result.push(nV3);
  44471. result.push(nV4);
  44472. result.push(nV3.clone());
  44473. result.push(nV2.clone());
  44474. break;
  44475. case 2:
  44476. if (!v1Out) {
  44477. nV1 = vertices[index].clone();
  44478. nV2 = clipVertices(nV1, vertices[index + 1]);
  44479. nV3 = clipVertices(nV1, vertices[index + 2]);
  44480. result.push(nV1);
  44481. result.push(nV2);
  44482. result.push(nV3);
  44483. }
  44484. if (!v2Out) {
  44485. nV1 = vertices[index + 1].clone();
  44486. nV2 = clipVertices(nV1, vertices[index + 2]);
  44487. nV3 = clipVertices(nV1, vertices[index]);
  44488. result.push(nV1);
  44489. result.push(nV2);
  44490. result.push(nV3);
  44491. }
  44492. if (!v3Out) {
  44493. nV1 = vertices[index + 2].clone();
  44494. nV2 = clipVertices(nV1, vertices[index]);
  44495. nV3 = clipVertices(nV1, vertices[index + 1]);
  44496. result.push(nV1);
  44497. result.push(nV2);
  44498. result.push(nV3);
  44499. }
  44500. break;
  44501. case 3:
  44502. break;
  44503. }
  44504. }
  44505. return result;
  44506. };
  44507. for (var index = 0; index < indices.length; index += 3) {
  44508. var faceVertices = new Array();
  44509. faceVertices.push(extractDecalVector3(index));
  44510. faceVertices.push(extractDecalVector3(index + 1));
  44511. faceVertices.push(extractDecalVector3(index + 2));
  44512. // Clip
  44513. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44514. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44515. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44516. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44517. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44518. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44519. if (faceVertices.length === 0) {
  44520. continue;
  44521. }
  44522. // Add UVs and get back to world
  44523. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44524. var vertex = faceVertices[vIndex];
  44525. //TODO check for Int32Array | Uint32Array | Uint16Array
  44526. vertexData.indices.push(currentVertexDataIndex);
  44527. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44528. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44529. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44530. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44531. currentVertexDataIndex++;
  44532. }
  44533. }
  44534. // Return mesh
  44535. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44536. vertexData.applyToMesh(decal);
  44537. decal.position = position.clone();
  44538. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44539. return decal;
  44540. };
  44541. // Privates
  44542. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44543. // extrusion geometry
  44544. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44545. var tangents = path3D.getTangents();
  44546. var normals = path3D.getNormals();
  44547. var binormals = path3D.getBinormals();
  44548. var distances = path3D.getDistances();
  44549. var angle = 0;
  44550. var returnScale = function () { return scale; };
  44551. var returnRotation = function () { return rotation; };
  44552. var rotate = custom ? rotateFunction : returnRotation;
  44553. var scl = custom ? scaleFunction : returnScale;
  44554. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44555. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44556. for (var i = 0; i < curve.length; i++) {
  44557. var shapePath = new Array();
  44558. var angleStep = rotate(i, distances[i]);
  44559. var scaleRatio = scl(i, distances[i]);
  44560. for (var p = 0; p < shape.length; p++) {
  44561. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  44562. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  44563. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  44564. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  44565. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  44566. shapePath[p] = rotated;
  44567. }
  44568. shapePaths[index] = shapePath;
  44569. angle += angleStep;
  44570. index++;
  44571. }
  44572. // cap
  44573. var capPath = function (shapePath) {
  44574. var pointCap = Array();
  44575. var barycenter = BABYLON.Vector3.Zero();
  44576. var i;
  44577. for (i = 0; i < shapePath.length; i++) {
  44578. barycenter.addInPlace(shapePath[i]);
  44579. }
  44580. barycenter.scaleInPlace(1.0 / shapePath.length);
  44581. for (i = 0; i < shapePath.length; i++) {
  44582. pointCap.push(barycenter);
  44583. }
  44584. return pointCap;
  44585. };
  44586. switch (cap) {
  44587. case BABYLON.Mesh.NO_CAP:
  44588. break;
  44589. case BABYLON.Mesh.CAP_START:
  44590. shapePaths[0] = capPath(shapePaths[2]);
  44591. shapePaths[1] = shapePaths[2];
  44592. break;
  44593. case BABYLON.Mesh.CAP_END:
  44594. shapePaths[index] = shapePaths[index - 1];
  44595. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44596. break;
  44597. case BABYLON.Mesh.CAP_ALL:
  44598. shapePaths[0] = capPath(shapePaths[2]);
  44599. shapePaths[1] = shapePaths[2];
  44600. shapePaths[index] = shapePaths[index - 1];
  44601. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44602. break;
  44603. default:
  44604. break;
  44605. }
  44606. return shapePaths;
  44607. };
  44608. var path3D;
  44609. var pathArray;
  44610. if (instance) {
  44611. path3D = (instance.path3D).update(curve);
  44612. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44613. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44614. return instance;
  44615. }
  44616. // extruded shape creation
  44617. path3D = new BABYLON.Path3D(curve);
  44618. var newShapePaths = new Array();
  44619. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44620. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44621. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44622. extrudedGeneric.pathArray = pathArray;
  44623. extrudedGeneric.path3D = path3D;
  44624. extrudedGeneric.cap = cap;
  44625. return extrudedGeneric;
  44626. };
  44627. return MeshBuilder;
  44628. }());
  44629. BABYLON.MeshBuilder = MeshBuilder;
  44630. })(BABYLON || (BABYLON = {}));
  44631. //# sourceMappingURL=babylon.meshBuilder.js.map
  44632. var BABYLON;
  44633. (function (BABYLON) {
  44634. var AudioEngine = (function () {
  44635. function AudioEngine() {
  44636. this._audioContext = null;
  44637. this._audioContextInitialized = false;
  44638. this.canUseWebAudio = false;
  44639. this.WarnedWebAudioUnsupported = false;
  44640. this.unlocked = false;
  44641. this.isMP3supported = false;
  44642. this.isOGGsupported = false;
  44643. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44644. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44645. this.canUseWebAudio = true;
  44646. }
  44647. var audioElem = document.createElement('audio');
  44648. try {
  44649. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44650. this.isMP3supported = true;
  44651. }
  44652. }
  44653. catch (e) {
  44654. // protect error during capability check.
  44655. }
  44656. try {
  44657. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44658. this.isOGGsupported = true;
  44659. }
  44660. }
  44661. catch (e) {
  44662. // protect error during capability check.
  44663. }
  44664. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44665. this._unlockiOSaudio();
  44666. }
  44667. else {
  44668. this.unlocked = true;
  44669. }
  44670. }
  44671. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44672. get: function () {
  44673. if (!this._audioContextInitialized) {
  44674. this._initializeAudioContext();
  44675. }
  44676. return this._audioContext;
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. AudioEngine.prototype._unlockiOSaudio = function () {
  44682. var _this = this;
  44683. var unlockaudio = function () {
  44684. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44685. var source = _this.audioContext.createBufferSource();
  44686. source.buffer = buffer;
  44687. source.connect(_this.audioContext.destination);
  44688. source.start(0);
  44689. setTimeout(function () {
  44690. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44691. _this.unlocked = true;
  44692. window.removeEventListener('touchend', unlockaudio, false);
  44693. if (_this.onAudioUnlocked) {
  44694. _this.onAudioUnlocked();
  44695. }
  44696. }
  44697. }, 0);
  44698. };
  44699. window.addEventListener('touchend', unlockaudio, false);
  44700. };
  44701. AudioEngine.prototype._initializeAudioContext = function () {
  44702. try {
  44703. if (this.canUseWebAudio) {
  44704. this._audioContext = new AudioContext();
  44705. // create a global volume gain node
  44706. this.masterGain = this._audioContext.createGain();
  44707. this.masterGain.gain.value = 1;
  44708. this.masterGain.connect(this._audioContext.destination);
  44709. this._audioContextInitialized = true;
  44710. }
  44711. }
  44712. catch (e) {
  44713. this.canUseWebAudio = false;
  44714. BABYLON.Tools.Error("Web Audio: " + e.message);
  44715. }
  44716. };
  44717. AudioEngine.prototype.dispose = function () {
  44718. if (this.canUseWebAudio && this._audioContextInitialized) {
  44719. if (this._connectedAnalyser) {
  44720. this._connectedAnalyser.stopDebugCanvas();
  44721. this._connectedAnalyser.dispose();
  44722. this.masterGain.disconnect();
  44723. this.masterGain.connect(this._audioContext.destination);
  44724. this._connectedAnalyser = null;
  44725. }
  44726. this.masterGain.gain.value = 1;
  44727. }
  44728. this.WarnedWebAudioUnsupported = false;
  44729. };
  44730. AudioEngine.prototype.getGlobalVolume = function () {
  44731. if (this.canUseWebAudio && this._audioContextInitialized) {
  44732. return this.masterGain.gain.value;
  44733. }
  44734. else {
  44735. return -1;
  44736. }
  44737. };
  44738. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44739. if (this.canUseWebAudio && this._audioContextInitialized) {
  44740. this.masterGain.gain.value = newVolume;
  44741. }
  44742. };
  44743. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44744. if (this._connectedAnalyser) {
  44745. this._connectedAnalyser.stopDebugCanvas();
  44746. }
  44747. if (this.canUseWebAudio && this._audioContextInitialized) {
  44748. this._connectedAnalyser = analyser;
  44749. this.masterGain.disconnect();
  44750. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44751. }
  44752. };
  44753. return AudioEngine;
  44754. }());
  44755. BABYLON.AudioEngine = AudioEngine;
  44756. })(BABYLON || (BABYLON = {}));
  44757. //# sourceMappingURL=babylon.audioEngine.js.map
  44758. var BABYLON;
  44759. (function (BABYLON) {
  44760. var Sound = (function () {
  44761. /**
  44762. * Create a sound and attach it to a scene
  44763. * @param name Name of your sound
  44764. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44765. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44766. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44767. */
  44768. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44769. var _this = this;
  44770. this.autoplay = false;
  44771. this.loop = false;
  44772. this.useCustomAttenuation = false;
  44773. this.spatialSound = false;
  44774. this.refDistance = 1;
  44775. this.rolloffFactor = 1;
  44776. this.maxDistance = 100;
  44777. this.distanceModel = "linear";
  44778. this._panningModel = "equalpower";
  44779. this._playbackRate = 1;
  44780. this._streaming = false;
  44781. this._startTime = 0;
  44782. this._startOffset = 0;
  44783. this._position = BABYLON.Vector3.Zero();
  44784. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44785. this._volume = 1;
  44786. this._isLoaded = false;
  44787. this._isReadyToPlay = false;
  44788. this.isPlaying = false;
  44789. this.isPaused = false;
  44790. this._isDirectional = false;
  44791. // Used if you'd like to create a directional sound.
  44792. // If not set, the sound will be omnidirectional
  44793. this._coneInnerAngle = 360;
  44794. this._coneOuterAngle = 360;
  44795. this._coneOuterGain = 0;
  44796. this._isOutputConnected = false;
  44797. this._urlType = "Unknown";
  44798. this.name = name;
  44799. this._scene = scene;
  44800. this._readyToPlayCallback = readyToPlayCallback;
  44801. // Default custom attenuation function is a linear attenuation
  44802. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44803. if (currentDistance < maxDistance) {
  44804. return currentVolume * (1 - currentDistance / maxDistance);
  44805. }
  44806. else {
  44807. return 0;
  44808. }
  44809. };
  44810. if (options) {
  44811. this.autoplay = options.autoplay || false;
  44812. this.loop = options.loop || false;
  44813. // if volume === 0, we need another way to check this option
  44814. if (options.volume !== undefined) {
  44815. this._volume = options.volume;
  44816. }
  44817. this.spatialSound = options.spatialSound || false;
  44818. this.maxDistance = options.maxDistance || 100;
  44819. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44820. this.rolloffFactor = options.rolloffFactor || 1;
  44821. this.refDistance = options.refDistance || 1;
  44822. this.distanceModel = options.distanceModel || "linear";
  44823. this._playbackRate = options.playbackRate || 1;
  44824. this._streaming = options.streaming || false;
  44825. }
  44826. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44827. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44828. this._soundGain.gain.value = this._volume;
  44829. this._inputAudioNode = this._soundGain;
  44830. this._ouputAudioNode = this._soundGain;
  44831. if (this.spatialSound) {
  44832. this._createSpatialParameters();
  44833. }
  44834. this._scene.mainSoundTrack.AddSound(this);
  44835. var validParameter = true;
  44836. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44837. if (urlOrArrayBuffer) {
  44838. if (typeof (urlOrArrayBuffer) === "string")
  44839. this._urlType = "String";
  44840. if (Array.isArray(urlOrArrayBuffer))
  44841. this._urlType = "Array";
  44842. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44843. this._urlType = "ArrayBuffer";
  44844. var urls = [];
  44845. var codecSupportedFound = false;
  44846. switch (this._urlType) {
  44847. case "ArrayBuffer":
  44848. if (urlOrArrayBuffer.byteLength > 0) {
  44849. codecSupportedFound = true;
  44850. this._soundLoaded(urlOrArrayBuffer);
  44851. }
  44852. break;
  44853. case "String":
  44854. urls.push(urlOrArrayBuffer);
  44855. case "Array":
  44856. if (urls.length === 0)
  44857. urls = urlOrArrayBuffer;
  44858. // If we found a supported format, we load it immediately and stop the loop
  44859. for (var i = 0; i < urls.length; i++) {
  44860. var url = urls[i];
  44861. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44862. codecSupportedFound = true;
  44863. }
  44864. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44865. codecSupportedFound = true;
  44866. }
  44867. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44868. codecSupportedFound = true;
  44869. }
  44870. if (url.indexOf("blob:") !== -1) {
  44871. codecSupportedFound = true;
  44872. }
  44873. if (codecSupportedFound) {
  44874. // Loading sound using XHR2
  44875. if (!this._streaming) {
  44876. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44877. }
  44878. else {
  44879. this._htmlAudioElement = new Audio(url);
  44880. this._htmlAudioElement.controls = false;
  44881. this._htmlAudioElement.loop = this.loop;
  44882. this._htmlAudioElement.crossOrigin = "anonymous";
  44883. this._htmlAudioElement.preload = "auto";
  44884. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44885. _this._isReadyToPlay = true;
  44886. if (_this.autoplay) {
  44887. _this.play();
  44888. }
  44889. if (_this._readyToPlayCallback) {
  44890. _this._readyToPlayCallback();
  44891. }
  44892. });
  44893. document.body.appendChild(this._htmlAudioElement);
  44894. }
  44895. break;
  44896. }
  44897. }
  44898. break;
  44899. default:
  44900. validParameter = false;
  44901. break;
  44902. }
  44903. if (!validParameter) {
  44904. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44905. }
  44906. else {
  44907. if (!codecSupportedFound) {
  44908. this._isReadyToPlay = true;
  44909. // Simulating a ready to play event to avoid breaking code path
  44910. if (this._readyToPlayCallback) {
  44911. window.setTimeout(function () {
  44912. _this._readyToPlayCallback();
  44913. }, 1000);
  44914. }
  44915. }
  44916. }
  44917. }
  44918. }
  44919. else {
  44920. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44921. this._scene.mainSoundTrack.AddSound(this);
  44922. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44923. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44924. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44925. }
  44926. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44927. if (this._readyToPlayCallback) {
  44928. window.setTimeout(function () {
  44929. _this._readyToPlayCallback();
  44930. }, 1000);
  44931. }
  44932. }
  44933. }
  44934. Sound.prototype.dispose = function () {
  44935. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44936. if (this.isPlaying) {
  44937. this.stop();
  44938. }
  44939. this._isReadyToPlay = false;
  44940. if (this.soundTrackId === -1) {
  44941. this._scene.mainSoundTrack.RemoveSound(this);
  44942. }
  44943. else {
  44944. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44945. }
  44946. if (this._soundGain) {
  44947. this._soundGain.disconnect();
  44948. this._soundGain = null;
  44949. }
  44950. if (this._soundPanner) {
  44951. this._soundPanner.disconnect();
  44952. this._soundPanner = null;
  44953. }
  44954. if (this._soundSource) {
  44955. this._soundSource.disconnect();
  44956. this._soundSource = null;
  44957. }
  44958. this._audioBuffer = null;
  44959. if (this._htmlAudioElement) {
  44960. this._htmlAudioElement.pause();
  44961. this._htmlAudioElement.src = "";
  44962. document.body.removeChild(this._htmlAudioElement);
  44963. }
  44964. if (this._connectedMesh) {
  44965. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44966. this._connectedMesh = null;
  44967. }
  44968. }
  44969. };
  44970. Sound.prototype.isReady = function () {
  44971. return this._isReadyToPlay;
  44972. };
  44973. Sound.prototype._soundLoaded = function (audioData) {
  44974. var _this = this;
  44975. this._isLoaded = true;
  44976. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44977. _this._audioBuffer = buffer;
  44978. _this._isReadyToPlay = true;
  44979. if (_this.autoplay) {
  44980. _this.play();
  44981. }
  44982. if (_this._readyToPlayCallback) {
  44983. _this._readyToPlayCallback();
  44984. }
  44985. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44986. };
  44987. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44989. this._audioBuffer = audioBuffer;
  44990. this._isReadyToPlay = true;
  44991. }
  44992. };
  44993. Sound.prototype.updateOptions = function (options) {
  44994. if (options) {
  44995. this.loop = options.loop || this.loop;
  44996. this.maxDistance = options.maxDistance || this.maxDistance;
  44997. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44998. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44999. this.refDistance = options.refDistance || this.refDistance;
  45000. this.distanceModel = options.distanceModel || this.distanceModel;
  45001. this._playbackRate = options.playbackRate || this._playbackRate;
  45002. this._updateSpatialParameters();
  45003. if (this.isPlaying) {
  45004. if (this._streaming) {
  45005. this._htmlAudioElement.playbackRate = this._playbackRate;
  45006. }
  45007. else {
  45008. this._soundSource.playbackRate.value = this._playbackRate;
  45009. }
  45010. }
  45011. }
  45012. };
  45013. Sound.prototype._createSpatialParameters = function () {
  45014. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45015. if (this._scene.headphone) {
  45016. this._panningModel = "HRTF";
  45017. }
  45018. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  45019. this._updateSpatialParameters();
  45020. this._soundPanner.connect(this._ouputAudioNode);
  45021. this._inputAudioNode = this._soundPanner;
  45022. }
  45023. };
  45024. Sound.prototype._updateSpatialParameters = function () {
  45025. if (this.spatialSound) {
  45026. if (this.useCustomAttenuation) {
  45027. // Tricks to disable in a way embedded Web Audio attenuation
  45028. this._soundPanner.distanceModel = "linear";
  45029. this._soundPanner.maxDistance = Number.MAX_VALUE;
  45030. this._soundPanner.refDistance = 1;
  45031. this._soundPanner.rolloffFactor = 1;
  45032. this._soundPanner.panningModel = this._panningModel;
  45033. }
  45034. else {
  45035. this._soundPanner.distanceModel = this.distanceModel;
  45036. this._soundPanner.maxDistance = this.maxDistance;
  45037. this._soundPanner.refDistance = this.refDistance;
  45038. this._soundPanner.rolloffFactor = this.rolloffFactor;
  45039. this._soundPanner.panningModel = this._panningModel;
  45040. }
  45041. }
  45042. };
  45043. Sound.prototype.switchPanningModelToHRTF = function () {
  45044. this._panningModel = "HRTF";
  45045. this._switchPanningModel();
  45046. };
  45047. Sound.prototype.switchPanningModelToEqualPower = function () {
  45048. this._panningModel = "equalpower";
  45049. this._switchPanningModel();
  45050. };
  45051. Sound.prototype._switchPanningModel = function () {
  45052. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45053. this._soundPanner.panningModel = this._panningModel;
  45054. }
  45055. };
  45056. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  45057. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45058. if (this._isOutputConnected) {
  45059. this._ouputAudioNode.disconnect();
  45060. }
  45061. this._ouputAudioNode.connect(soundTrackAudioNode);
  45062. this._isOutputConnected = true;
  45063. }
  45064. };
  45065. /**
  45066. * Transform this sound into a directional source
  45067. * @param coneInnerAngle Size of the inner cone in degree
  45068. * @param coneOuterAngle Size of the outer cone in degree
  45069. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  45070. */
  45071. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  45072. if (coneOuterAngle < coneInnerAngle) {
  45073. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  45074. return;
  45075. }
  45076. this._coneInnerAngle = coneInnerAngle;
  45077. this._coneOuterAngle = coneOuterAngle;
  45078. this._coneOuterGain = coneOuterGain;
  45079. this._isDirectional = true;
  45080. if (this.isPlaying && this.loop) {
  45081. this.stop();
  45082. this.play();
  45083. }
  45084. };
  45085. Sound.prototype.setPosition = function (newPosition) {
  45086. this._position = newPosition;
  45087. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45088. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45089. }
  45090. };
  45091. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  45092. this._localDirection = newLocalDirection;
  45093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  45094. this._updateDirection();
  45095. }
  45096. };
  45097. Sound.prototype._updateDirection = function () {
  45098. var mat = this._connectedMesh.getWorldMatrix();
  45099. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  45100. direction.normalize();
  45101. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  45102. };
  45103. Sound.prototype.updateDistanceFromListener = function () {
  45104. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  45105. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  45106. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  45107. }
  45108. };
  45109. Sound.prototype.setAttenuationFunction = function (callback) {
  45110. this._customAttenuationFunction = callback;
  45111. };
  45112. /**
  45113. * Play the sound
  45114. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  45115. * @param offset (optional) Start the sound setting it at a specific time
  45116. */
  45117. Sound.prototype.play = function (time, offset) {
  45118. var _this = this;
  45119. if (this._isReadyToPlay && this._scene.audioEnabled) {
  45120. try {
  45121. if (this._startOffset < 0) {
  45122. time = -this._startOffset;
  45123. this._startOffset = 0;
  45124. }
  45125. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45126. if (!this._soundSource || !this._streamingSource) {
  45127. if (this.spatialSound) {
  45128. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45129. if (this._isDirectional) {
  45130. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45131. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45132. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45133. if (this._connectedMesh) {
  45134. this._updateDirection();
  45135. }
  45136. else {
  45137. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45138. }
  45139. }
  45140. }
  45141. }
  45142. if (this._streaming) {
  45143. if (!this._streamingSource) {
  45144. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45145. this._htmlAudioElement.onended = function () { _this._onended(); };
  45146. this._htmlAudioElement.playbackRate = this._playbackRate;
  45147. }
  45148. this._streamingSource.disconnect();
  45149. this._streamingSource.connect(this._inputAudioNode);
  45150. this._htmlAudioElement.play();
  45151. }
  45152. else {
  45153. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45154. this._soundSource.buffer = this._audioBuffer;
  45155. this._soundSource.connect(this._inputAudioNode);
  45156. this._soundSource.loop = this.loop;
  45157. this._soundSource.playbackRate.value = this._playbackRate;
  45158. this._soundSource.onended = function () { _this._onended(); };
  45159. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45160. }
  45161. this._startTime = startTime;
  45162. this.isPlaying = true;
  45163. this.isPaused = false;
  45164. }
  45165. catch (ex) {
  45166. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45167. }
  45168. }
  45169. };
  45170. Sound.prototype._onended = function () {
  45171. this.isPlaying = false;
  45172. if (this.onended) {
  45173. this.onended();
  45174. }
  45175. };
  45176. /**
  45177. * Stop the sound
  45178. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45179. */
  45180. Sound.prototype.stop = function (time) {
  45181. if (this.isPlaying) {
  45182. if (this._streaming) {
  45183. this._htmlAudioElement.pause();
  45184. // Test needed for Firefox or it will generate an Invalid State Error
  45185. if (this._htmlAudioElement.currentTime > 0) {
  45186. this._htmlAudioElement.currentTime = 0;
  45187. }
  45188. }
  45189. else {
  45190. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45191. this._soundSource.stop(stopTime);
  45192. this._soundSource.onended = null;
  45193. if (!this.isPaused) {
  45194. this._startOffset = 0;
  45195. }
  45196. }
  45197. this.isPlaying = false;
  45198. }
  45199. };
  45200. Sound.prototype.pause = function () {
  45201. if (this.isPlaying) {
  45202. this.isPaused = true;
  45203. if (this._streaming) {
  45204. this._htmlAudioElement.pause();
  45205. }
  45206. else {
  45207. this.stop(0);
  45208. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45209. }
  45210. }
  45211. };
  45212. Sound.prototype.setVolume = function (newVolume, time) {
  45213. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45214. if (time) {
  45215. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45216. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45217. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45218. }
  45219. else {
  45220. this._soundGain.gain.value = newVolume;
  45221. }
  45222. }
  45223. this._volume = newVolume;
  45224. };
  45225. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45226. this._playbackRate = newPlaybackRate;
  45227. if (this.isPlaying) {
  45228. if (this._streaming) {
  45229. this._htmlAudioElement.playbackRate = this._playbackRate;
  45230. }
  45231. else {
  45232. this._soundSource.playbackRate.value = this._playbackRate;
  45233. }
  45234. }
  45235. };
  45236. Sound.prototype.getVolume = function () {
  45237. return this._volume;
  45238. };
  45239. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45240. var _this = this;
  45241. if (this._connectedMesh) {
  45242. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45243. this._registerFunc = null;
  45244. }
  45245. this._connectedMesh = meshToConnectTo;
  45246. if (!this.spatialSound) {
  45247. this.spatialSound = true;
  45248. this._createSpatialParameters();
  45249. if (this.isPlaying && this.loop) {
  45250. this.stop();
  45251. this.play();
  45252. }
  45253. }
  45254. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45255. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45256. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45257. };
  45258. Sound.prototype.detachFromMesh = function () {
  45259. if (this._connectedMesh) {
  45260. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45261. this._registerFunc = null;
  45262. this._connectedMesh = null;
  45263. }
  45264. };
  45265. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45266. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45267. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45268. this._updateDirection();
  45269. }
  45270. };
  45271. Sound.prototype.clone = function () {
  45272. var _this = this;
  45273. if (!this._streaming) {
  45274. var setBufferAndRun = function () {
  45275. if (_this._isReadyToPlay) {
  45276. clonedSound._audioBuffer = _this.getAudioBuffer();
  45277. clonedSound._isReadyToPlay = true;
  45278. if (clonedSound.autoplay) {
  45279. clonedSound.play();
  45280. }
  45281. }
  45282. else {
  45283. window.setTimeout(setBufferAndRun, 300);
  45284. }
  45285. };
  45286. var currentOptions = {
  45287. autoplay: this.autoplay, loop: this.loop,
  45288. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45289. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45290. refDistance: this.refDistance, distanceModel: this.distanceModel
  45291. };
  45292. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45293. if (this.useCustomAttenuation) {
  45294. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45295. }
  45296. clonedSound.setPosition(this._position);
  45297. clonedSound.setPlaybackRate(this._playbackRate);
  45298. setBufferAndRun();
  45299. return clonedSound;
  45300. }
  45301. else {
  45302. return null;
  45303. }
  45304. };
  45305. Sound.prototype.getAudioBuffer = function () {
  45306. return this._audioBuffer;
  45307. };
  45308. Sound.prototype.serialize = function () {
  45309. var serializationObject = {
  45310. name: this.name,
  45311. url: this.name,
  45312. autoplay: this.autoplay,
  45313. loop: this.loop,
  45314. volume: this._volume,
  45315. spatialSound: this.spatialSound,
  45316. maxDistance: this.maxDistance,
  45317. rolloffFactor: this.rolloffFactor,
  45318. refDistance: this.refDistance,
  45319. distanceModel: this.distanceModel,
  45320. playbackRate: this._playbackRate,
  45321. panningModel: this._panningModel,
  45322. soundTrackId: this.soundTrackId
  45323. };
  45324. if (this.spatialSound) {
  45325. if (this._connectedMesh)
  45326. serializationObject.connectedMeshId = this._connectedMesh.id;
  45327. serializationObject.position = this._position.asArray();
  45328. serializationObject.refDistance = this.refDistance;
  45329. serializationObject.distanceModel = this.distanceModel;
  45330. serializationObject.isDirectional = this._isDirectional;
  45331. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45332. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45333. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45334. serializationObject.coneOuterGain = this._coneOuterGain;
  45335. }
  45336. return serializationObject;
  45337. };
  45338. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45339. var soundName = parsedSound.name;
  45340. var soundUrl;
  45341. if (parsedSound.url) {
  45342. soundUrl = rootUrl + parsedSound.url;
  45343. }
  45344. else {
  45345. soundUrl = rootUrl + soundName;
  45346. }
  45347. var options = {
  45348. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45349. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45350. rolloffFactor: parsedSound.rolloffFactor,
  45351. refDistance: parsedSound.refDistance,
  45352. distanceModel: parsedSound.distanceModel,
  45353. playbackRate: parsedSound.playbackRate
  45354. };
  45355. var newSound;
  45356. if (!sourceSound) {
  45357. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45358. scene._addPendingData(newSound);
  45359. }
  45360. else {
  45361. var setBufferAndRun = function () {
  45362. if (sourceSound._isReadyToPlay) {
  45363. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45364. newSound._isReadyToPlay = true;
  45365. if (newSound.autoplay) {
  45366. newSound.play();
  45367. }
  45368. }
  45369. else {
  45370. window.setTimeout(setBufferAndRun, 300);
  45371. }
  45372. };
  45373. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45374. setBufferAndRun();
  45375. }
  45376. if (parsedSound.position) {
  45377. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45378. newSound.setPosition(soundPosition);
  45379. }
  45380. if (parsedSound.isDirectional) {
  45381. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45382. if (parsedSound.localDirectionToMesh) {
  45383. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45384. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45385. }
  45386. }
  45387. if (parsedSound.connectedMeshId) {
  45388. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45389. if (connectedMesh) {
  45390. newSound.attachToMesh(connectedMesh);
  45391. }
  45392. }
  45393. return newSound;
  45394. };
  45395. return Sound;
  45396. }());
  45397. BABYLON.Sound = Sound;
  45398. })(BABYLON || (BABYLON = {}));
  45399. //# sourceMappingURL=babylon.sound.js.map
  45400. var BABYLON;
  45401. (function (BABYLON) {
  45402. var SoundTrack = (function () {
  45403. function SoundTrack(scene, options) {
  45404. this.id = -1;
  45405. this._isMainTrack = false;
  45406. this._isInitialized = false;
  45407. this._scene = scene;
  45408. this.soundCollection = new Array();
  45409. this._options = options;
  45410. if (!this._isMainTrack) {
  45411. this._scene.soundTracks.push(this);
  45412. this.id = this._scene.soundTracks.length - 1;
  45413. }
  45414. }
  45415. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45417. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45418. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45419. if (this._options) {
  45420. if (this._options.volume) {
  45421. this._outputAudioNode.gain.value = this._options.volume;
  45422. }
  45423. if (this._options.mainTrack) {
  45424. this._isMainTrack = this._options.mainTrack;
  45425. }
  45426. }
  45427. this._isInitialized = true;
  45428. }
  45429. };
  45430. SoundTrack.prototype.dispose = function () {
  45431. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45432. if (this._connectedAnalyser) {
  45433. this._connectedAnalyser.stopDebugCanvas();
  45434. }
  45435. while (this.soundCollection.length) {
  45436. this.soundCollection[0].dispose();
  45437. }
  45438. if (this._outputAudioNode) {
  45439. this._outputAudioNode.disconnect();
  45440. }
  45441. this._outputAudioNode = null;
  45442. }
  45443. };
  45444. SoundTrack.prototype.AddSound = function (sound) {
  45445. if (!this._isInitialized) {
  45446. this._initializeSoundTrackAudioGraph();
  45447. }
  45448. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45449. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45450. }
  45451. if (sound.soundTrackId) {
  45452. if (sound.soundTrackId === -1) {
  45453. this._scene.mainSoundTrack.RemoveSound(sound);
  45454. }
  45455. else {
  45456. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45457. }
  45458. }
  45459. this.soundCollection.push(sound);
  45460. sound.soundTrackId = this.id;
  45461. };
  45462. SoundTrack.prototype.RemoveSound = function (sound) {
  45463. var index = this.soundCollection.indexOf(sound);
  45464. if (index !== -1) {
  45465. this.soundCollection.splice(index, 1);
  45466. }
  45467. };
  45468. SoundTrack.prototype.setVolume = function (newVolume) {
  45469. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45470. this._outputAudioNode.gain.value = newVolume;
  45471. }
  45472. };
  45473. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45474. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45475. for (var i = 0; i < this.soundCollection.length; i++) {
  45476. this.soundCollection[i].switchPanningModelToHRTF();
  45477. }
  45478. }
  45479. };
  45480. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45481. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45482. for (var i = 0; i < this.soundCollection.length; i++) {
  45483. this.soundCollection[i].switchPanningModelToEqualPower();
  45484. }
  45485. }
  45486. };
  45487. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45488. if (this._connectedAnalyser) {
  45489. this._connectedAnalyser.stopDebugCanvas();
  45490. }
  45491. this._connectedAnalyser = analyser;
  45492. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45493. this._outputAudioNode.disconnect();
  45494. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45495. }
  45496. };
  45497. return SoundTrack;
  45498. }());
  45499. BABYLON.SoundTrack = SoundTrack;
  45500. })(BABYLON || (BABYLON = {}));
  45501. //# sourceMappingURL=babylon.soundtrack.js.map
  45502. var BABYLON;
  45503. (function (BABYLON) {
  45504. var Analyser = (function () {
  45505. function Analyser(scene) {
  45506. this.SMOOTHING = 0.75;
  45507. this.FFT_SIZE = 512;
  45508. this.BARGRAPHAMPLITUDE = 256;
  45509. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45510. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45511. this._scene = scene;
  45512. this._audioEngine = BABYLON.Engine.audioEngine;
  45513. if (this._audioEngine.canUseWebAudio) {
  45514. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45515. this._webAudioAnalyser.minDecibels = -140;
  45516. this._webAudioAnalyser.maxDecibels = 0;
  45517. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45518. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45519. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45520. }
  45521. }
  45522. Analyser.prototype.getFrequencyBinCount = function () {
  45523. if (this._audioEngine.canUseWebAudio) {
  45524. return this._webAudioAnalyser.frequencyBinCount;
  45525. }
  45526. else {
  45527. return 0;
  45528. }
  45529. };
  45530. Analyser.prototype.getByteFrequencyData = function () {
  45531. if (this._audioEngine.canUseWebAudio) {
  45532. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45533. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45534. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45535. }
  45536. return this._byteFreqs;
  45537. };
  45538. Analyser.prototype.getByteTimeDomainData = function () {
  45539. if (this._audioEngine.canUseWebAudio) {
  45540. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45541. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45542. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45543. }
  45544. return this._byteTime;
  45545. };
  45546. Analyser.prototype.getFloatFrequencyData = function () {
  45547. if (this._audioEngine.canUseWebAudio) {
  45548. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45549. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45550. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45551. }
  45552. return this._floatFreqs;
  45553. };
  45554. Analyser.prototype.drawDebugCanvas = function () {
  45555. var _this = this;
  45556. if (this._audioEngine.canUseWebAudio) {
  45557. if (!this._debugCanvas) {
  45558. this._debugCanvas = document.createElement("canvas");
  45559. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45560. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45561. this._debugCanvas.style.position = "absolute";
  45562. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45563. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45564. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45565. document.body.appendChild(this._debugCanvas);
  45566. this._registerFunc = function () {
  45567. _this.drawDebugCanvas();
  45568. };
  45569. this._scene.registerBeforeRender(this._registerFunc);
  45570. }
  45571. if (this._registerFunc) {
  45572. var workingArray = this.getByteFrequencyData();
  45573. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45574. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45575. // Draw the frequency domain chart.
  45576. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45577. var value = workingArray[i];
  45578. var percent = value / this.BARGRAPHAMPLITUDE;
  45579. var height = this.DEBUGCANVASSIZE.height * percent;
  45580. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45581. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45582. var hue = i / this.getFrequencyBinCount() * 360;
  45583. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45584. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45585. }
  45586. }
  45587. }
  45588. };
  45589. Analyser.prototype.stopDebugCanvas = function () {
  45590. if (this._debugCanvas) {
  45591. this._scene.unregisterBeforeRender(this._registerFunc);
  45592. this._registerFunc = null;
  45593. document.body.removeChild(this._debugCanvas);
  45594. this._debugCanvas = null;
  45595. this._debugCanvasContext = null;
  45596. }
  45597. };
  45598. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45599. if (this._audioEngine.canUseWebAudio) {
  45600. inputAudioNode.connect(this._webAudioAnalyser);
  45601. this._webAudioAnalyser.connect(outputAudioNode);
  45602. }
  45603. };
  45604. Analyser.prototype.dispose = function () {
  45605. if (this._audioEngine.canUseWebAudio) {
  45606. this._webAudioAnalyser.disconnect();
  45607. }
  45608. };
  45609. return Analyser;
  45610. }());
  45611. BABYLON.Analyser = Analyser;
  45612. })(BABYLON || (BABYLON = {}));
  45613. //# sourceMappingURL=babylon.analyser.js.map
  45614. var BABYLON;
  45615. (function (BABYLON) {
  45616. var CubeTexture = (function (_super) {
  45617. __extends(CubeTexture, _super);
  45618. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45619. if (onLoad === void 0) { onLoad = null; }
  45620. if (onError === void 0) { onError = null; }
  45621. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45622. if (prefiltered === void 0) { prefiltered = false; }
  45623. if (forcedExtension === void 0) { forcedExtension = null; }
  45624. var _this = _super.call(this, scene) || this;
  45625. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45626. _this.name = rootUrl;
  45627. _this.url = rootUrl;
  45628. _this._noMipmap = noMipmap;
  45629. _this.hasAlpha = false;
  45630. _this._format = format;
  45631. _this._prefiltered = prefiltered;
  45632. _this.isCube = true;
  45633. _this._textureMatrix = BABYLON.Matrix.Identity();
  45634. if (prefiltered) {
  45635. _this.gammaSpace = false;
  45636. }
  45637. if (!rootUrl && !files) {
  45638. return _this;
  45639. }
  45640. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45641. if (!files) {
  45642. if (!extensions) {
  45643. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45644. }
  45645. files = [];
  45646. for (var index = 0; index < extensions.length; index++) {
  45647. files.push(rootUrl + extensions[index]);
  45648. }
  45649. _this._extensions = extensions;
  45650. }
  45651. _this._files = files;
  45652. if (!_this._texture) {
  45653. if (!scene.useDelayedTextureLoading) {
  45654. if (prefiltered) {
  45655. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45656. }
  45657. else {
  45658. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45659. }
  45660. }
  45661. else {
  45662. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45663. }
  45664. }
  45665. else if (onLoad) {
  45666. if (_this._texture.isReady) {
  45667. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45668. }
  45669. else {
  45670. _this._texture.onLoadedObservable.add(onLoad);
  45671. }
  45672. }
  45673. return _this;
  45674. }
  45675. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45676. return new CubeTexture("", scene, null, noMipmap, files);
  45677. };
  45678. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45679. if (forcedExtension === void 0) { forcedExtension = null; }
  45680. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45681. };
  45682. // Methods
  45683. CubeTexture.prototype.delayLoad = function () {
  45684. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45685. return;
  45686. }
  45687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45688. this._texture = this._getFromCache(this.url, this._noMipmap);
  45689. if (!this._texture) {
  45690. if (this._prefiltered) {
  45691. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45692. }
  45693. else {
  45694. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45695. }
  45696. }
  45697. };
  45698. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45699. return this._textureMatrix;
  45700. };
  45701. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45702. this._textureMatrix = value;
  45703. };
  45704. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45705. var texture = BABYLON.SerializationHelper.Parse(function () {
  45706. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45707. }, parsedTexture, scene);
  45708. // Animations
  45709. if (parsedTexture.animations) {
  45710. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45711. var parsedAnimation = parsedTexture.animations[animationIndex];
  45712. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45713. }
  45714. }
  45715. return texture;
  45716. };
  45717. CubeTexture.prototype.clone = function () {
  45718. var _this = this;
  45719. return BABYLON.SerializationHelper.Clone(function () {
  45720. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45721. }, this);
  45722. };
  45723. return CubeTexture;
  45724. }(BABYLON.BaseTexture));
  45725. BABYLON.CubeTexture = CubeTexture;
  45726. })(BABYLON || (BABYLON = {}));
  45727. //# sourceMappingURL=babylon.cubeTexture.js.map
  45728. var BABYLON;
  45729. (function (BABYLON) {
  45730. var RenderTargetTexture = (function (_super) {
  45731. __extends(RenderTargetTexture, _super);
  45732. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45733. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45734. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45735. if (isCube === void 0) { isCube = false; }
  45736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45737. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45738. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45739. if (isMulti === void 0) { isMulti = false; }
  45740. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45741. _this.isCube = isCube;
  45742. /**
  45743. * Use this list to define the list of mesh you want to render.
  45744. */
  45745. _this.renderList = new Array();
  45746. _this.renderParticles = true;
  45747. _this.renderSprites = false;
  45748. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45749. _this.ignoreCameraViewport = false;
  45750. // Events
  45751. /**
  45752. * An event triggered when the texture is unbind.
  45753. * @type {BABYLON.Observable}
  45754. */
  45755. _this.onBeforeBindObservable = new BABYLON.Observable();
  45756. /**
  45757. * An event triggered when the texture is unbind.
  45758. * @type {BABYLON.Observable}
  45759. */
  45760. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45761. /**
  45762. * An event triggered before rendering the texture
  45763. * @type {BABYLON.Observable}
  45764. */
  45765. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45766. /**
  45767. * An event triggered after rendering the texture
  45768. * @type {BABYLON.Observable}
  45769. */
  45770. _this.onAfterRenderObservable = new BABYLON.Observable();
  45771. /**
  45772. * An event triggered after the texture clear
  45773. * @type {BABYLON.Observable}
  45774. */
  45775. _this.onClearObservable = new BABYLON.Observable();
  45776. _this._currentRefreshId = -1;
  45777. _this._refreshRate = 1;
  45778. _this._samples = 1;
  45779. scene = _this.getScene();
  45780. _this.name = name;
  45781. _this.isRenderTarget = true;
  45782. _this._size = size;
  45783. _this._generateMipMaps = generateMipMaps;
  45784. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45785. // Rendering groups
  45786. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45787. if (isMulti) {
  45788. return _this;
  45789. }
  45790. _this._renderTargetOptions = {
  45791. generateMipMaps: generateMipMaps,
  45792. type: type,
  45793. samplingMode: samplingMode,
  45794. generateDepthBuffer: generateDepthBuffer,
  45795. generateStencilBuffer: generateStencilBuffer
  45796. };
  45797. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45798. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45799. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45800. }
  45801. if (isCube) {
  45802. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  45803. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  45804. _this._textureMatrix = BABYLON.Matrix.Identity();
  45805. }
  45806. else {
  45807. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  45808. }
  45809. return _this;
  45810. }
  45811. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  45812. get: function () {
  45813. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  45814. },
  45815. enumerable: true,
  45816. configurable: true
  45817. });
  45818. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  45819. get: function () {
  45820. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  45826. get: function () {
  45827. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  45833. set: function (callback) {
  45834. if (this._onAfterUnbindObserver) {
  45835. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  45836. }
  45837. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  45838. },
  45839. enumerable: true,
  45840. configurable: true
  45841. });
  45842. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  45843. set: function (callback) {
  45844. if (this._onBeforeRenderObserver) {
  45845. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45846. }
  45847. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  45853. set: function (callback) {
  45854. if (this._onAfterRenderObserver) {
  45855. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45856. }
  45857. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45858. },
  45859. enumerable: true,
  45860. configurable: true
  45861. });
  45862. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  45863. set: function (callback) {
  45864. if (this._onClearObserver) {
  45865. this.onClearObservable.remove(this._onClearObserver);
  45866. }
  45867. this._onClearObserver = this.onClearObservable.add(callback);
  45868. },
  45869. enumerable: true,
  45870. configurable: true
  45871. });
  45872. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  45873. get: function () {
  45874. return this._renderTargetOptions;
  45875. },
  45876. enumerable: true,
  45877. configurable: true
  45878. });
  45879. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  45880. get: function () {
  45881. return this._samples;
  45882. },
  45883. set: function (value) {
  45884. if (this._samples === value) {
  45885. return;
  45886. }
  45887. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  45888. },
  45889. enumerable: true,
  45890. configurable: true
  45891. });
  45892. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  45893. this._currentRefreshId = -1;
  45894. };
  45895. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  45896. get: function () {
  45897. return this._refreshRate;
  45898. },
  45899. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  45900. set: function (value) {
  45901. this._refreshRate = value;
  45902. this.resetRefreshCounter();
  45903. },
  45904. enumerable: true,
  45905. configurable: true
  45906. });
  45907. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  45908. if (!this._postProcessManager) {
  45909. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  45910. this._postProcesses = new Array();
  45911. }
  45912. this._postProcesses.push(postProcess);
  45913. this._postProcesses[0].autoClear = false;
  45914. };
  45915. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  45916. if (!this._postProcesses) {
  45917. return;
  45918. }
  45919. if (dispose) {
  45920. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  45921. var postProcess = _a[_i];
  45922. postProcess.dispose();
  45923. postProcess = null;
  45924. }
  45925. }
  45926. this._postProcesses = [];
  45927. };
  45928. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  45929. if (!this._postProcesses) {
  45930. return;
  45931. }
  45932. var index = this._postProcesses.indexOf(postProcess);
  45933. if (index === -1) {
  45934. return;
  45935. }
  45936. this._postProcesses.splice(index, 1);
  45937. if (this._postProcesses.length > 0) {
  45938. this._postProcesses[0].autoClear = false;
  45939. }
  45940. };
  45941. RenderTargetTexture.prototype._shouldRender = function () {
  45942. if (this._currentRefreshId === -1) {
  45943. this._currentRefreshId = 1;
  45944. return true;
  45945. }
  45946. if (this.refreshRate === this._currentRefreshId) {
  45947. this._currentRefreshId = 1;
  45948. return true;
  45949. }
  45950. this._currentRefreshId++;
  45951. return false;
  45952. };
  45953. RenderTargetTexture.prototype.getRenderSize = function () {
  45954. return this._size;
  45955. };
  45956. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  45957. get: function () {
  45958. return true;
  45959. },
  45960. enumerable: true,
  45961. configurable: true
  45962. });
  45963. RenderTargetTexture.prototype.scale = function (ratio) {
  45964. var newSize = this._size * ratio;
  45965. this.resize(newSize);
  45966. };
  45967. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  45968. if (this.isCube) {
  45969. return this._textureMatrix;
  45970. }
  45971. return _super.prototype.getReflectionTextureMatrix.call(this);
  45972. };
  45973. RenderTargetTexture.prototype.resize = function (size) {
  45974. this.releaseInternalTexture();
  45975. if (this.isCube) {
  45976. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  45977. }
  45978. else {
  45979. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  45980. }
  45981. };
  45982. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  45983. var scene = this.getScene();
  45984. var engine = scene.getEngine();
  45985. if (this.useCameraPostProcesses !== undefined) {
  45986. useCameraPostProcess = this.useCameraPostProcesses;
  45987. }
  45988. if (this._waitingRenderList) {
  45989. this.renderList = [];
  45990. for (var index = 0; index < this._waitingRenderList.length; index++) {
  45991. var id = this._waitingRenderList[index];
  45992. this.renderList.push(scene.getMeshByID(id));
  45993. }
  45994. delete this._waitingRenderList;
  45995. }
  45996. // Is predicate defined?
  45997. if (this.renderListPredicate) {
  45998. this.renderList.splice(0); // Clear previous renderList
  45999. var sceneMeshes = this.getScene().meshes;
  46000. for (var index = 0; index < sceneMeshes.length; index++) {
  46001. var mesh = sceneMeshes[index];
  46002. if (this.renderListPredicate(mesh)) {
  46003. this.renderList.push(mesh);
  46004. }
  46005. }
  46006. }
  46007. if (this.renderList && this.renderList.length === 0) {
  46008. return;
  46009. }
  46010. this.onBeforeBindObservable.notifyObservers(this);
  46011. // Set custom projection.
  46012. // Needs to be before binding to prevent changing the aspect ratio.
  46013. var camera;
  46014. if (this.activeCamera) {
  46015. camera = this.activeCamera;
  46016. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  46017. if (this.activeCamera !== scene.activeCamera) {
  46018. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  46019. }
  46020. }
  46021. else {
  46022. camera = scene.activeCamera;
  46023. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  46024. }
  46025. // Prepare renderingManager
  46026. this._renderingManager.reset();
  46027. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  46028. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  46029. var sceneRenderId = scene.getRenderId();
  46030. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  46031. var mesh = currentRenderList[meshIndex];
  46032. if (mesh) {
  46033. if (!mesh.isReady()) {
  46034. // Reset _currentRefreshId
  46035. this.resetRefreshCounter();
  46036. continue;
  46037. }
  46038. mesh._preActivateForIntermediateRendering(sceneRenderId);
  46039. var isMasked = void 0;
  46040. if (!this.renderList) {
  46041. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  46042. }
  46043. else {
  46044. isMasked = false;
  46045. }
  46046. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  46047. mesh._activate(sceneRenderId);
  46048. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  46049. var subMesh = mesh.subMeshes[subIndex];
  46050. scene._activeIndices.addCount(subMesh.indexCount, false);
  46051. this._renderingManager.dispatch(subMesh);
  46052. }
  46053. }
  46054. }
  46055. }
  46056. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  46057. var particleSystem = scene.particleSystems[particleIndex];
  46058. var emitter = particleSystem.emitter;
  46059. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  46060. continue;
  46061. }
  46062. if (currentRenderList.indexOf(emitter) >= 0) {
  46063. this._renderingManager.dispatchParticles(particleSystem);
  46064. }
  46065. }
  46066. if (this.isCube) {
  46067. for (var face = 0; face < 6; face++) {
  46068. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46069. scene.incrementRenderId();
  46070. scene.resetCachedMaterial();
  46071. }
  46072. }
  46073. else {
  46074. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46075. }
  46076. this.onAfterUnbindObservable.notifyObservers(this);
  46077. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  46078. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  46079. }
  46080. engine.setViewport(scene.activeCamera.viewport);
  46081. scene.resetCachedMaterial();
  46082. };
  46083. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  46084. var _this = this;
  46085. var scene = this.getScene();
  46086. var engine = scene.getEngine();
  46087. // Bind
  46088. if (this._postProcessManager) {
  46089. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  46090. }
  46091. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  46092. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  46093. }
  46094. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  46095. // Clear
  46096. if (this.onClearObservable.hasObservers()) {
  46097. this.onClearObservable.notifyObservers(engine);
  46098. }
  46099. else {
  46100. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  46101. }
  46102. if (!this._doNotChangeAspectRatio) {
  46103. scene.updateTransformMatrix(true);
  46104. }
  46105. // Render
  46106. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  46107. if (this._postProcessManager) {
  46108. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  46109. }
  46110. else if (useCameraPostProcess) {
  46111. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  46112. }
  46113. if (!this._doNotChangeAspectRatio) {
  46114. scene.updateTransformMatrix(true);
  46115. }
  46116. // Dump ?
  46117. if (dumpForDebug) {
  46118. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  46119. }
  46120. // Unbind
  46121. if (!this.isCube || faceIndex === 5) {
  46122. if (this.isCube) {
  46123. if (faceIndex === 5) {
  46124. engine.generateMipMapsForCubemap(this._texture);
  46125. }
  46126. }
  46127. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  46128. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  46129. });
  46130. }
  46131. else {
  46132. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46133. }
  46134. };
  46135. /**
  46136. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46137. * This allowed control for front to back rendering or reversly depending of the special needs.
  46138. *
  46139. * @param renderingGroupId The rendering group id corresponding to its index
  46140. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46141. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46142. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46143. */
  46144. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46145. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46146. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46147. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46148. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46149. };
  46150. /**
  46151. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46152. *
  46153. * @param renderingGroupId The rendering group id corresponding to its index
  46154. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46155. */
  46156. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46157. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46158. };
  46159. RenderTargetTexture.prototype.clone = function () {
  46160. var textureSize = this.getSize();
  46161. 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);
  46162. // Base texture
  46163. newTexture.hasAlpha = this.hasAlpha;
  46164. newTexture.level = this.level;
  46165. // RenderTarget Texture
  46166. newTexture.coordinatesMode = this.coordinatesMode;
  46167. newTexture.renderList = this.renderList.slice(0);
  46168. return newTexture;
  46169. };
  46170. RenderTargetTexture.prototype.serialize = function () {
  46171. if (!this.name) {
  46172. return null;
  46173. }
  46174. var serializationObject = _super.prototype.serialize.call(this);
  46175. serializationObject.renderTargetSize = this.getRenderSize();
  46176. serializationObject.renderList = [];
  46177. for (var index = 0; index < this.renderList.length; index++) {
  46178. serializationObject.renderList.push(this.renderList[index].id);
  46179. }
  46180. return serializationObject;
  46181. };
  46182. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46183. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46184. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46185. };
  46186. RenderTargetTexture.prototype.dispose = function () {
  46187. if (this._postProcessManager) {
  46188. this._postProcessManager.dispose();
  46189. this._postProcessManager = null;
  46190. }
  46191. this.clearPostProcesses(true);
  46192. this.renderList = null;
  46193. // Remove from custom render targets
  46194. var scene = this.getScene();
  46195. var index = scene.customRenderTargets.indexOf(this);
  46196. if (index >= 0) {
  46197. scene.customRenderTargets.splice(index, 1);
  46198. }
  46199. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46200. var camera = _a[_i];
  46201. index = camera.customRenderTargets.indexOf(this);
  46202. if (index >= 0) {
  46203. camera.customRenderTargets.splice(index, 1);
  46204. }
  46205. }
  46206. _super.prototype.dispose.call(this);
  46207. };
  46208. RenderTargetTexture.prototype._rebuild = function () {
  46209. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46210. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46211. }
  46212. if (this._postProcessManager) {
  46213. this._postProcessManager._rebuild();
  46214. }
  46215. };
  46216. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46217. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46218. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46219. return RenderTargetTexture;
  46220. }(BABYLON.Texture));
  46221. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46222. })(BABYLON || (BABYLON = {}));
  46223. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46224. var BABYLON;
  46225. (function (BABYLON) {
  46226. ;
  46227. var MultiRenderTarget = (function (_super) {
  46228. __extends(MultiRenderTarget, _super);
  46229. function MultiRenderTarget(name, size, count, scene, options) {
  46230. var _this = this;
  46231. options = options || {};
  46232. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46233. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46234. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46235. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46236. if (!_this.isSupported) {
  46237. _this.dispose();
  46238. return;
  46239. }
  46240. var types = [];
  46241. var samplingModes = [];
  46242. for (var i = 0; i < count; i++) {
  46243. if (options.types && options.types[i]) {
  46244. types.push(options.types[i]);
  46245. }
  46246. else {
  46247. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46248. }
  46249. if (options.samplingModes && options.samplingModes[i]) {
  46250. samplingModes.push(options.samplingModes[i]);
  46251. }
  46252. else {
  46253. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46254. }
  46255. }
  46256. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46257. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46258. _this._count = count;
  46259. _this._size = size;
  46260. _this._multiRenderTargetOptions = {
  46261. samplingModes: samplingModes,
  46262. generateMipMaps: generateMipMaps,
  46263. generateDepthBuffer: generateDepthBuffer,
  46264. generateStencilBuffer: generateStencilBuffer,
  46265. generateDepthTexture: generateDepthTexture,
  46266. types: types,
  46267. textureCount: count
  46268. };
  46269. _this._createInternalTextures();
  46270. _this._createTextures();
  46271. return _this;
  46272. }
  46273. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46274. get: function () {
  46275. var engine = this.getScene().getEngine();
  46276. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46277. },
  46278. enumerable: true,
  46279. configurable: true
  46280. });
  46281. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46282. get: function () {
  46283. return this._textures;
  46284. },
  46285. enumerable: true,
  46286. configurable: true
  46287. });
  46288. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46289. get: function () {
  46290. return this._textures[this._textures.length - 1];
  46291. },
  46292. enumerable: true,
  46293. configurable: true
  46294. });
  46295. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46296. set: function (wrap) {
  46297. if (this._textures) {
  46298. for (var i = 0; i < this._textures.length; i++) {
  46299. this._textures[i].wrapU = wrap;
  46300. }
  46301. }
  46302. },
  46303. enumerable: true,
  46304. configurable: true
  46305. });
  46306. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46307. set: function (wrap) {
  46308. if (this._textures) {
  46309. for (var i = 0; i < this._textures.length; i++) {
  46310. this._textures[i].wrapV = wrap;
  46311. }
  46312. }
  46313. },
  46314. enumerable: true,
  46315. configurable: true
  46316. });
  46317. MultiRenderTarget.prototype._rebuild = function () {
  46318. this.releaseInternalTextures();
  46319. this._createInternalTextures();
  46320. for (var i = 0; i < this._internalTextures.length; i++) {
  46321. var texture = this._textures[i];
  46322. texture._texture = this._internalTextures[i];
  46323. }
  46324. // Keeps references to frame buffer and stencil/depth buffer
  46325. this._texture = this._internalTextures[0];
  46326. };
  46327. MultiRenderTarget.prototype._createInternalTextures = function () {
  46328. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46329. };
  46330. MultiRenderTarget.prototype._createTextures = function () {
  46331. this._textures = [];
  46332. for (var i = 0; i < this._internalTextures.length; i++) {
  46333. var texture = new BABYLON.Texture(null, this.getScene());
  46334. texture._texture = this._internalTextures[i];
  46335. this._textures.push(texture);
  46336. }
  46337. // Keeps references to frame buffer and stencil/depth buffer
  46338. this._texture = this._internalTextures[0];
  46339. };
  46340. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46341. get: function () {
  46342. return this._samples;
  46343. },
  46344. set: function (value) {
  46345. if (this._samples === value) {
  46346. return;
  46347. }
  46348. for (var i = 0; i < this._internalTextures.length; i++) {
  46349. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46350. }
  46351. },
  46352. enumerable: true,
  46353. configurable: true
  46354. });
  46355. MultiRenderTarget.prototype.resize = function (size) {
  46356. this.releaseInternalTextures();
  46357. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46358. this._createInternalTextures();
  46359. };
  46360. MultiRenderTarget.prototype.dispose = function () {
  46361. this.releaseInternalTextures();
  46362. _super.prototype.dispose.call(this);
  46363. };
  46364. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46365. if (!this._internalTextures) {
  46366. return;
  46367. }
  46368. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46369. if (this._internalTextures[i] !== undefined) {
  46370. this._internalTextures[i].dispose();
  46371. this._internalTextures.splice(i, 1);
  46372. }
  46373. }
  46374. };
  46375. return MultiRenderTarget;
  46376. }(BABYLON.RenderTargetTexture));
  46377. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46378. })(BABYLON || (BABYLON = {}));
  46379. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46380. /// <reference path="babylon.renderTargetTexture.ts" />
  46381. var BABYLON;
  46382. (function (BABYLON) {
  46383. var MirrorTexture = (function (_super) {
  46384. __extends(MirrorTexture, _super);
  46385. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46386. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46387. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46388. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46389. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46390. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46391. _this._transformMatrix = BABYLON.Matrix.Zero();
  46392. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46393. _this._blurKernelX = 0;
  46394. _this._blurKernelY = 0;
  46395. _this._blurRatio = 1.0;
  46396. _this.ignoreCameraViewport = true;
  46397. _this.onBeforeRenderObservable.add(function () {
  46398. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46399. _this._savedViewMatrix = scene.getViewMatrix();
  46400. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46401. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46402. scene.clipPlane = _this.mirrorPlane;
  46403. scene.getEngine().cullBackFaces = false;
  46404. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46405. });
  46406. _this.onAfterRenderObservable.add(function () {
  46407. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46408. scene.getEngine().cullBackFaces = true;
  46409. scene._mirroredCameraPosition = null;
  46410. delete scene.clipPlane;
  46411. });
  46412. return _this;
  46413. }
  46414. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46415. get: function () {
  46416. return this._blurRatio;
  46417. },
  46418. set: function (value) {
  46419. if (this._blurRatio === value) {
  46420. return;
  46421. }
  46422. this._blurRatio = value;
  46423. this._preparePostProcesses();
  46424. },
  46425. enumerable: true,
  46426. configurable: true
  46427. });
  46428. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46429. set: function (value) {
  46430. this.blurKernelX = value;
  46431. this.blurKernelY = value;
  46432. },
  46433. enumerable: true,
  46434. configurable: true
  46435. });
  46436. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46437. get: function () {
  46438. return this._blurKernelX;
  46439. },
  46440. set: function (value) {
  46441. if (this._blurKernelX === value) {
  46442. return;
  46443. }
  46444. this._blurKernelX = value;
  46445. this._preparePostProcesses();
  46446. },
  46447. enumerable: true,
  46448. configurable: true
  46449. });
  46450. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46451. get: function () {
  46452. return this._blurKernelY;
  46453. },
  46454. set: function (value) {
  46455. if (this._blurKernelY === value) {
  46456. return;
  46457. }
  46458. this._blurKernelY = value;
  46459. this._preparePostProcesses();
  46460. },
  46461. enumerable: true,
  46462. configurable: true
  46463. });
  46464. MirrorTexture.prototype._preparePostProcesses = function () {
  46465. this.clearPostProcesses(true);
  46466. if (this._blurKernelX && this._blurKernelY) {
  46467. var engine = this.getScene().getEngine();
  46468. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46469. 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);
  46470. this._blurX.autoClear = false;
  46471. if (this._blurRatio === 1 && this.samples < 2) {
  46472. this._blurX.outputTexture = this._texture;
  46473. }
  46474. else {
  46475. this._blurX.alwaysForcePOT = true;
  46476. }
  46477. 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);
  46478. this._blurY.autoClear = false;
  46479. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  46480. this.addPostProcess(this._blurX);
  46481. this.addPostProcess(this._blurY);
  46482. }
  46483. };
  46484. MirrorTexture.prototype.clone = function () {
  46485. var textureSize = this.getSize();
  46486. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  46487. // Base texture
  46488. newTexture.hasAlpha = this.hasAlpha;
  46489. newTexture.level = this.level;
  46490. // Mirror Texture
  46491. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46492. newTexture.renderList = this.renderList.slice(0);
  46493. return newTexture;
  46494. };
  46495. MirrorTexture.prototype.serialize = function () {
  46496. if (!this.name) {
  46497. return null;
  46498. }
  46499. var serializationObject = _super.prototype.serialize.call(this);
  46500. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46501. return serializationObject;
  46502. };
  46503. return MirrorTexture;
  46504. }(BABYLON.RenderTargetTexture));
  46505. BABYLON.MirrorTexture = MirrorTexture;
  46506. })(BABYLON || (BABYLON = {}));
  46507. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46508. /// <reference path="babylon.renderTargetTexture.ts" />
  46509. var BABYLON;
  46510. (function (BABYLON) {
  46511. /**
  46512. * Creates a refraction texture used by refraction channel of the standard material.
  46513. * @param name the texture name
  46514. * @param size size of the underlying texture
  46515. * @param scene root scene
  46516. */
  46517. var RefractionTexture = (function (_super) {
  46518. __extends(RefractionTexture, _super);
  46519. function RefractionTexture(name, size, scene, generateMipMaps) {
  46520. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46521. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46522. _this.depth = 2.0;
  46523. _this.onBeforeRenderObservable.add(function () {
  46524. scene.clipPlane = _this.refractionPlane;
  46525. });
  46526. _this.onAfterRenderObservable.add(function () {
  46527. delete scene.clipPlane;
  46528. });
  46529. return _this;
  46530. }
  46531. RefractionTexture.prototype.clone = function () {
  46532. var textureSize = this.getSize();
  46533. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46534. // Base texture
  46535. newTexture.hasAlpha = this.hasAlpha;
  46536. newTexture.level = this.level;
  46537. // Refraction Texture
  46538. newTexture.refractionPlane = this.refractionPlane.clone();
  46539. newTexture.renderList = this.renderList.slice(0);
  46540. newTexture.depth = this.depth;
  46541. return newTexture;
  46542. };
  46543. RefractionTexture.prototype.serialize = function () {
  46544. if (!this.name) {
  46545. return null;
  46546. }
  46547. var serializationObject = _super.prototype.serialize.call(this);
  46548. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  46549. serializationObject.depth = this.depth;
  46550. return serializationObject;
  46551. };
  46552. return RefractionTexture;
  46553. }(BABYLON.RenderTargetTexture));
  46554. BABYLON.RefractionTexture = RefractionTexture;
  46555. })(BABYLON || (BABYLON = {}));
  46556. //# sourceMappingURL=babylon.refractionTexture.js.map
  46557. /// <reference path="babylon.texture.ts" />
  46558. var BABYLON;
  46559. (function (BABYLON) {
  46560. var DynamicTexture = (function (_super) {
  46561. __extends(DynamicTexture, _super);
  46562. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  46563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46564. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46565. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  46566. _this.name = name;
  46567. var engine = _this.getScene().getEngine();
  46568. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46569. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46570. _this._generateMipMaps = generateMipMaps;
  46571. if (options.getContext) {
  46572. _this._canvas = options;
  46573. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46574. }
  46575. else {
  46576. _this._canvas = document.createElement("canvas");
  46577. if (options.width) {
  46578. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46579. }
  46580. else {
  46581. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  46582. }
  46583. }
  46584. var textureSize = _this.getSize();
  46585. _this._canvas.width = textureSize.width;
  46586. _this._canvas.height = textureSize.height;
  46587. _this._context = _this._canvas.getContext("2d");
  46588. return _this;
  46589. }
  46590. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  46591. get: function () {
  46592. return true;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. DynamicTexture.prototype._recreate = function (textureSize) {
  46598. this._canvas.width = textureSize.width;
  46599. this._canvas.height = textureSize.height;
  46600. this.releaseInternalTexture();
  46601. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  46602. };
  46603. DynamicTexture.prototype.scale = function (ratio) {
  46604. var textureSize = this.getSize();
  46605. textureSize.width *= ratio;
  46606. textureSize.height *= ratio;
  46607. this._recreate(textureSize);
  46608. };
  46609. DynamicTexture.prototype.scaleTo = function (width, height) {
  46610. var textureSize = this.getSize();
  46611. textureSize.width = width;
  46612. textureSize.height = height;
  46613. this._recreate(textureSize);
  46614. };
  46615. DynamicTexture.prototype.getContext = function () {
  46616. return this._context;
  46617. };
  46618. DynamicTexture.prototype.clear = function () {
  46619. var size = this.getSize();
  46620. this._context.fillRect(0, 0, size.width, size.height);
  46621. };
  46622. DynamicTexture.prototype.update = function (invertY) {
  46623. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  46624. };
  46625. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  46626. if (update === void 0) { update = true; }
  46627. var size = this.getSize();
  46628. if (clearColor) {
  46629. this._context.fillStyle = clearColor;
  46630. this._context.fillRect(0, 0, size.width, size.height);
  46631. }
  46632. this._context.font = font;
  46633. if (x === null || x === undefined) {
  46634. var textSize = this._context.measureText(text);
  46635. x = (size.width - textSize.width) / 2;
  46636. }
  46637. if (y === null || y === undefined) {
  46638. var fontSize = parseInt((font.replace(/\D/g, '')));
  46639. ;
  46640. y = (size.height / 2) + (fontSize / 3.65);
  46641. }
  46642. this._context.fillStyle = color;
  46643. this._context.fillText(text, x, y);
  46644. if (update) {
  46645. this.update(invertY);
  46646. }
  46647. };
  46648. DynamicTexture.prototype.clone = function () {
  46649. var textureSize = this.getSize();
  46650. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46651. // Base texture
  46652. newTexture.hasAlpha = this.hasAlpha;
  46653. newTexture.level = this.level;
  46654. // Dynamic Texture
  46655. newTexture.wrapU = this.wrapU;
  46656. newTexture.wrapV = this.wrapV;
  46657. return newTexture;
  46658. };
  46659. DynamicTexture.prototype._rebuild = function () {
  46660. this.update();
  46661. };
  46662. return DynamicTexture;
  46663. }(BABYLON.Texture));
  46664. BABYLON.DynamicTexture = DynamicTexture;
  46665. })(BABYLON || (BABYLON = {}));
  46666. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46667. var BABYLON;
  46668. (function (BABYLON) {
  46669. var VideoTexture = (function (_super) {
  46670. __extends(VideoTexture, _super);
  46671. /**
  46672. * Creates a video texture.
  46673. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46674. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46675. * @param {BABYLON.Scene} scene is obviously the current scene.
  46676. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46677. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46678. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46679. */
  46680. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46681. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46682. if (invertY === void 0) { invertY = false; }
  46683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46684. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46685. _this._autoLaunch = true;
  46686. var urls;
  46687. _this.name = name;
  46688. if (urlsOrVideo instanceof HTMLVideoElement) {
  46689. _this.video = urlsOrVideo;
  46690. }
  46691. else {
  46692. urls = urlsOrVideo;
  46693. _this.video = document.createElement("video");
  46694. _this.video.autoplay = false;
  46695. _this.video.loop = true;
  46696. }
  46697. _this._generateMipMaps = generateMipMaps;
  46698. _this._samplingMode = samplingMode;
  46699. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46700. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46701. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46702. }
  46703. else {
  46704. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46705. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46706. _this._generateMipMaps = false;
  46707. }
  46708. if (urls) {
  46709. _this.video.addEventListener("canplay", function () {
  46710. _this._createTexture();
  46711. });
  46712. urls.forEach(function (url) {
  46713. var source = document.createElement("source");
  46714. source.src = url;
  46715. _this.video.appendChild(source);
  46716. });
  46717. }
  46718. else {
  46719. _this._createTexture();
  46720. }
  46721. _this._lastUpdate = BABYLON.Tools.Now;
  46722. return _this;
  46723. }
  46724. VideoTexture.prototype.__setTextureReady = function () {
  46725. this._texture.isReady = true;
  46726. };
  46727. VideoTexture.prototype._createTexture = function () {
  46728. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46729. if (this._autoLaunch) {
  46730. this._autoLaunch = false;
  46731. this.video.play();
  46732. }
  46733. this._setTextureReady = this.__setTextureReady.bind(this);
  46734. this.video.addEventListener("playing", this._setTextureReady);
  46735. };
  46736. VideoTexture.prototype._rebuild = function () {
  46737. this.update();
  46738. };
  46739. VideoTexture.prototype.update = function () {
  46740. var now = BABYLON.Tools.Now;
  46741. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46742. return false;
  46743. }
  46744. this._lastUpdate = now;
  46745. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46746. return true;
  46747. };
  46748. VideoTexture.prototype.dispose = function () {
  46749. _super.prototype.dispose.call(this);
  46750. this.video.removeEventListener("playing", this._setTextureReady);
  46751. };
  46752. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46753. var video = document.createElement("video");
  46754. var constraintsDeviceId;
  46755. if (constraints && constraints.deviceId) {
  46756. constraintsDeviceId = {
  46757. exact: constraints.deviceId
  46758. };
  46759. }
  46760. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46761. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46762. if (navigator.getUserMedia) {
  46763. navigator.getUserMedia({
  46764. video: {
  46765. deviceId: constraintsDeviceId,
  46766. width: {
  46767. min: (constraints && constraints.minWidth) || 256,
  46768. max: (constraints && constraints.maxWidth) || 640
  46769. },
  46770. height: {
  46771. min: (constraints && constraints.minHeight) || 256,
  46772. max: (constraints && constraints.maxHeight) || 480
  46773. }
  46774. }
  46775. }, function (stream) {
  46776. if (video.mozSrcObject !== undefined) {
  46777. video.mozSrcObject = stream;
  46778. }
  46779. else {
  46780. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46781. }
  46782. video.play();
  46783. if (onReady) {
  46784. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46785. }
  46786. }, function (e) {
  46787. BABYLON.Tools.Error(e.name);
  46788. });
  46789. }
  46790. };
  46791. return VideoTexture;
  46792. }(BABYLON.Texture));
  46793. BABYLON.VideoTexture = VideoTexture;
  46794. })(BABYLON || (BABYLON = {}));
  46795. //# sourceMappingURL=babylon.videoTexture.js.map
  46796. var BABYLON;
  46797. (function (BABYLON) {
  46798. var RawTexture = (function (_super) {
  46799. __extends(RawTexture, _super);
  46800. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46801. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46802. if (invertY === void 0) { invertY = false; }
  46803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46804. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46805. _this.format = format;
  46806. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46807. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46808. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46809. return _this;
  46810. }
  46811. RawTexture.prototype.update = function (data) {
  46812. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46813. };
  46814. // Statics
  46815. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46816. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46817. if (invertY === void 0) { invertY = false; }
  46818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46819. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46820. };
  46821. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46822. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46823. if (invertY === void 0) { invertY = false; }
  46824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46825. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46826. };
  46827. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46828. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46829. if (invertY === void 0) { invertY = false; }
  46830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46831. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46832. };
  46833. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46834. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46835. if (invertY === void 0) { invertY = false; }
  46836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46837. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46838. };
  46839. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46840. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46841. if (invertY === void 0) { invertY = false; }
  46842. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46843. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46844. };
  46845. return RawTexture;
  46846. }(BABYLON.Texture));
  46847. BABYLON.RawTexture = RawTexture;
  46848. })(BABYLON || (BABYLON = {}));
  46849. //# sourceMappingURL=babylon.rawTexture.js.map
  46850. var BABYLON;
  46851. (function (BABYLON) {
  46852. var PostProcess = (function () {
  46853. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  46854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  46855. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46856. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  46857. if (blockCompilation === void 0) { blockCompilation = false; }
  46858. this.name = name;
  46859. this.width = -1;
  46860. this.height = -1;
  46861. this.autoClear = true;
  46862. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  46863. /*
  46864. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  46865. Can only be used on a single postprocess or on the last one of a chain.
  46866. */
  46867. this.enablePixelPerfectMode = false;
  46868. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  46869. this.alwaysForcePOT = false;
  46870. this.samples = 1;
  46871. this.adaptScaleToCurrentViewport = false;
  46872. this._reusable = false;
  46873. this._textures = new BABYLON.SmartArray(2);
  46874. this._currentRenderTextureInd = 0;
  46875. this._scaleRatio = new BABYLON.Vector2(1, 1);
  46876. this._texelSize = BABYLON.Vector2.Zero();
  46877. // Events
  46878. /**
  46879. * An event triggered when the postprocess is activated.
  46880. * @type {BABYLON.Observable}
  46881. */
  46882. this.onActivateObservable = new BABYLON.Observable();
  46883. /**
  46884. * An event triggered when the postprocess changes its size.
  46885. * @type {BABYLON.Observable}
  46886. */
  46887. this.onSizeChangedObservable = new BABYLON.Observable();
  46888. /**
  46889. * An event triggered when the postprocess applies its effect.
  46890. * @type {BABYLON.Observable}
  46891. */
  46892. this.onApplyObservable = new BABYLON.Observable();
  46893. /**
  46894. * An event triggered before rendering the postprocess
  46895. * @type {BABYLON.Observable}
  46896. */
  46897. this.onBeforeRenderObservable = new BABYLON.Observable();
  46898. /**
  46899. * An event triggered after rendering the postprocess
  46900. * @type {BABYLON.Observable}
  46901. */
  46902. this.onAfterRenderObservable = new BABYLON.Observable();
  46903. if (camera != null) {
  46904. this._camera = camera;
  46905. this._scene = camera.getScene();
  46906. camera.attachPostProcess(this);
  46907. this._engine = this._scene.getEngine();
  46908. this._scene.postProcesses.push(this);
  46909. }
  46910. else {
  46911. this._engine = engine;
  46912. this._engine.postProcesses.push(this);
  46913. }
  46914. this._options = options;
  46915. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  46916. this._reusable = reusable || false;
  46917. this._textureType = textureType;
  46918. this._samplers = samplers || [];
  46919. this._samplers.push("textureSampler");
  46920. this._fragmentUrl = fragmentUrl;
  46921. this._vertexUrl = vertexUrl;
  46922. this._parameters = parameters || [];
  46923. this._parameters.push("scale");
  46924. this._indexParameters = indexParameters;
  46925. if (!blockCompilation) {
  46926. this.updateEffect(defines);
  46927. }
  46928. }
  46929. Object.defineProperty(PostProcess.prototype, "onActivate", {
  46930. set: function (callback) {
  46931. if (this._onActivateObserver) {
  46932. this.onActivateObservable.remove(this._onActivateObserver);
  46933. }
  46934. this._onActivateObserver = this.onActivateObservable.add(callback);
  46935. },
  46936. enumerable: true,
  46937. configurable: true
  46938. });
  46939. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  46940. set: function (callback) {
  46941. if (this._onSizeChangedObserver) {
  46942. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  46943. }
  46944. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  46945. },
  46946. enumerable: true,
  46947. configurable: true
  46948. });
  46949. Object.defineProperty(PostProcess.prototype, "onApply", {
  46950. set: function (callback) {
  46951. if (this._onApplyObserver) {
  46952. this.onApplyObservable.remove(this._onApplyObserver);
  46953. }
  46954. this._onApplyObserver = this.onApplyObservable.add(callback);
  46955. },
  46956. enumerable: true,
  46957. configurable: true
  46958. });
  46959. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  46960. set: function (callback) {
  46961. if (this._onBeforeRenderObserver) {
  46962. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46963. }
  46964. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46965. },
  46966. enumerable: true,
  46967. configurable: true
  46968. });
  46969. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  46970. set: function (callback) {
  46971. if (this._onAfterRenderObserver) {
  46972. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46973. }
  46974. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46975. },
  46976. enumerable: true,
  46977. configurable: true
  46978. });
  46979. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  46980. get: function () {
  46981. return this._textures.data[this._currentRenderTextureInd];
  46982. },
  46983. set: function (value) {
  46984. this._forcedOutputTexture = value;
  46985. },
  46986. enumerable: true,
  46987. configurable: true
  46988. });
  46989. PostProcess.prototype.getCamera = function () {
  46990. return this._camera;
  46991. };
  46992. Object.defineProperty(PostProcess.prototype, "texelSize", {
  46993. get: function () {
  46994. if (this._shareOutputWithPostProcess) {
  46995. return this._shareOutputWithPostProcess.texelSize;
  46996. }
  46997. if (this._forcedOutputTexture) {
  46998. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  46999. }
  47000. return this._texelSize;
  47001. },
  47002. enumerable: true,
  47003. configurable: true
  47004. });
  47005. PostProcess.prototype.getEngine = function () {
  47006. return this._engine;
  47007. };
  47008. PostProcess.prototype.getEffect = function () {
  47009. return this._effect;
  47010. };
  47011. PostProcess.prototype.shareOutputWith = function (postProcess) {
  47012. this._disposeTextures();
  47013. this._shareOutputWithPostProcess = postProcess;
  47014. return this;
  47015. };
  47016. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  47017. 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);
  47018. };
  47019. PostProcess.prototype.isReusable = function () {
  47020. return this._reusable;
  47021. };
  47022. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  47023. PostProcess.prototype.markTextureDirty = function () {
  47024. this.width = -1;
  47025. };
  47026. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  47027. var _this = this;
  47028. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  47029. camera = camera || this._camera;
  47030. var scene = camera.getScene();
  47031. var engine = scene.getEngine();
  47032. var maxSize = engine.getCaps().maxTextureSize;
  47033. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  47034. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  47035. var desiredWidth = (this._options.width || requiredWidth);
  47036. var desiredHeight = this._options.height || requiredHeight;
  47037. if (this.adaptScaleToCurrentViewport) {
  47038. var currentViewport = engine.currentViewport;
  47039. if (currentViewport) {
  47040. desiredWidth *= currentViewport.width;
  47041. desiredHeight *= currentViewport.height;
  47042. }
  47043. }
  47044. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  47045. if (!this._options.width) {
  47046. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  47047. }
  47048. if (!this._options.height) {
  47049. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  47050. }
  47051. }
  47052. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  47053. if (this._textures.length > 0) {
  47054. for (var i = 0; i < this._textures.length; i++) {
  47055. this._engine._releaseTexture(this._textures.data[i]);
  47056. }
  47057. this._textures.reset();
  47058. }
  47059. this.width = desiredWidth;
  47060. this.height = desiredHeight;
  47061. var textureSize = { width: this.width, height: this.height };
  47062. var textureOptions = {
  47063. generateMipMaps: false,
  47064. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  47065. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  47066. samplingMode: this.renderTargetSamplingMode,
  47067. type: this._textureType
  47068. };
  47069. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47070. if (this._reusable) {
  47071. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47072. }
  47073. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  47074. this.onSizeChangedObservable.notifyObservers(this);
  47075. }
  47076. this._textures.forEach(function (texture) {
  47077. if (texture.samples !== _this.samples) {
  47078. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  47079. }
  47080. });
  47081. }
  47082. var target;
  47083. if (this._shareOutputWithPostProcess) {
  47084. target = this._shareOutputWithPostProcess.outputTexture;
  47085. }
  47086. else if (this._forcedOutputTexture) {
  47087. target = this._forcedOutputTexture;
  47088. this.width = this._forcedOutputTexture.width;
  47089. this.height = this._forcedOutputTexture.height;
  47090. }
  47091. else {
  47092. target = this.outputTexture;
  47093. }
  47094. if (this.enablePixelPerfectMode) {
  47095. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  47096. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  47097. }
  47098. else {
  47099. this._scaleRatio.copyFromFloats(1, 1);
  47100. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  47101. }
  47102. this.onActivateObservable.notifyObservers(camera);
  47103. // Clear
  47104. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  47105. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  47106. }
  47107. if (this._reusable) {
  47108. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  47109. }
  47110. };
  47111. Object.defineProperty(PostProcess.prototype, "isSupported", {
  47112. get: function () {
  47113. return this._effect.isSupported;
  47114. },
  47115. enumerable: true,
  47116. configurable: true
  47117. });
  47118. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  47119. get: function () {
  47120. if (this._shareOutputWithPostProcess) {
  47121. return this._shareOutputWithPostProcess.aspectRatio;
  47122. }
  47123. if (this._forcedOutputTexture) {
  47124. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  47125. }
  47126. return this.width / this.height;
  47127. },
  47128. enumerable: true,
  47129. configurable: true
  47130. });
  47131. PostProcess.prototype.apply = function () {
  47132. // Check
  47133. if (!this._effect || !this._effect.isReady())
  47134. return null;
  47135. // States
  47136. this._engine.enableEffect(this._effect);
  47137. this._engine.setState(false);
  47138. this._engine.setDepthBuffer(false);
  47139. this._engine.setDepthWrite(false);
  47140. // Alpha
  47141. this._engine.setAlphaMode(this.alphaMode);
  47142. if (this.alphaConstants) {
  47143. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47144. }
  47145. // Texture
  47146. var source;
  47147. if (this._shareOutputWithPostProcess) {
  47148. source = this._shareOutputWithPostProcess.outputTexture;
  47149. }
  47150. else if (this._forcedOutputTexture) {
  47151. source = this._forcedOutputTexture;
  47152. }
  47153. else {
  47154. source = this.outputTexture;
  47155. }
  47156. this._effect._bindTexture("textureSampler", source);
  47157. // Parameters
  47158. this._effect.setVector2("scale", this._scaleRatio);
  47159. this.onApplyObservable.notifyObservers(this._effect);
  47160. return this._effect;
  47161. };
  47162. PostProcess.prototype._disposeTextures = function () {
  47163. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47164. return;
  47165. }
  47166. if (this._textures.length > 0) {
  47167. for (var i = 0; i < this._textures.length; i++) {
  47168. this._engine._releaseTexture(this._textures.data[i]);
  47169. }
  47170. }
  47171. this._textures.dispose();
  47172. };
  47173. PostProcess.prototype.dispose = function (camera) {
  47174. camera = camera || this._camera;
  47175. this._disposeTextures();
  47176. if (this._scene) {
  47177. var index_1 = this._scene.postProcesses.indexOf(this);
  47178. if (index_1 !== -1) {
  47179. this._scene.postProcesses.splice(index_1, 1);
  47180. }
  47181. }
  47182. else {
  47183. var index_2 = this._engine.postProcesses.indexOf(this);
  47184. if (index_2 !== -1) {
  47185. this._engine.postProcesses.splice(index_2, 1);
  47186. }
  47187. }
  47188. if (!camera) {
  47189. return;
  47190. }
  47191. camera.detachPostProcess(this);
  47192. var index = camera._postProcesses.indexOf(this);
  47193. if (index === 0 && camera._postProcesses.length > 0) {
  47194. this._camera._postProcesses[0].markTextureDirty();
  47195. }
  47196. this.onActivateObservable.clear();
  47197. this.onAfterRenderObservable.clear();
  47198. this.onApplyObservable.clear();
  47199. this.onBeforeRenderObservable.clear();
  47200. this.onSizeChangedObservable.clear();
  47201. };
  47202. return PostProcess;
  47203. }());
  47204. BABYLON.PostProcess = PostProcess;
  47205. })(BABYLON || (BABYLON = {}));
  47206. //# sourceMappingURL=babylon.postProcess.js.map
  47207. var BABYLON;
  47208. (function (BABYLON) {
  47209. var PassPostProcess = (function (_super) {
  47210. __extends(PassPostProcess, _super);
  47211. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47212. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47213. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47214. }
  47215. return PassPostProcess;
  47216. }(BABYLON.PostProcess));
  47217. BABYLON.PassPostProcess = PassPostProcess;
  47218. })(BABYLON || (BABYLON = {}));
  47219. //# sourceMappingURL=babylon.passPostProcess.js.map
  47220. var BABYLON;
  47221. (function (BABYLON) {
  47222. var ShadowGenerator = (function () {
  47223. /**
  47224. * Creates a ShadowGenerator object.
  47225. * A ShadowGenerator is the required tool to use the shadows.
  47226. * Each light casting shadows needs to use its own ShadowGenerator.
  47227. * Required parameters :
  47228. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47229. * - `light`: the light object generating the shadows.
  47230. * - `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.
  47231. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47232. */
  47233. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47234. // Members
  47235. this._bias = 0.00005;
  47236. this._blurBoxOffset = 1;
  47237. this._blurScale = 2;
  47238. this._blurKernel = 1;
  47239. this._useKernelBlur = false;
  47240. this._filter = ShadowGenerator.FILTER_NONE;
  47241. this._darkness = 0;
  47242. this._transparencyShadow = false;
  47243. /**
  47244. * Controls the extent to which the shadows fade out at the edge of the frustum
  47245. * Used only by directionals and spots
  47246. */
  47247. this.frustumEdgeFalloff = 0;
  47248. this.forceBackFacesOnly = false;
  47249. this._lightDirection = BABYLON.Vector3.Zero();
  47250. this._viewMatrix = BABYLON.Matrix.Zero();
  47251. this._projectionMatrix = BABYLON.Matrix.Zero();
  47252. this._transformMatrix = BABYLON.Matrix.Zero();
  47253. this._worldViewProjection = BABYLON.Matrix.Zero();
  47254. this._currentFaceIndex = 0;
  47255. this._currentFaceIndexCache = 0;
  47256. this._isCube = false;
  47257. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47258. this._mapSize = mapSize;
  47259. this._light = light;
  47260. this._scene = light.getScene();
  47261. light._shadowGenerator = this;
  47262. // Texture type fallback from float to int if not supported.
  47263. var caps = this._scene.getEngine().getCaps();
  47264. if (!useFullFloatFirst) {
  47265. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47266. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47267. }
  47268. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47269. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47270. }
  47271. else {
  47272. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47273. }
  47274. }
  47275. else {
  47276. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47277. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47278. }
  47279. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47280. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47281. }
  47282. else {
  47283. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47284. }
  47285. }
  47286. this._initializeGenerator();
  47287. }
  47288. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47289. // Static
  47290. get: function () {
  47291. return ShadowGenerator._FILTER_NONE;
  47292. },
  47293. enumerable: true,
  47294. configurable: true
  47295. });
  47296. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47297. get: function () {
  47298. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47299. },
  47300. enumerable: true,
  47301. configurable: true
  47302. });
  47303. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47304. get: function () {
  47305. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47306. },
  47307. enumerable: true,
  47308. configurable: true
  47309. });
  47310. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47311. get: function () {
  47312. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47313. },
  47314. enumerable: true,
  47315. configurable: true
  47316. });
  47317. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47318. get: function () {
  47319. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47320. },
  47321. enumerable: true,
  47322. configurable: true
  47323. });
  47324. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47325. get: function () {
  47326. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47327. },
  47328. enumerable: true,
  47329. configurable: true
  47330. });
  47331. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47332. get: function () {
  47333. return this._bias;
  47334. },
  47335. set: function (bias) {
  47336. this._bias = bias;
  47337. },
  47338. enumerable: true,
  47339. configurable: true
  47340. });
  47341. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47342. get: function () {
  47343. return this._blurBoxOffset;
  47344. },
  47345. set: function (value) {
  47346. if (this._blurBoxOffset === value) {
  47347. return;
  47348. }
  47349. this._blurBoxOffset = value;
  47350. this._disposeBlurPostProcesses();
  47351. },
  47352. enumerable: true,
  47353. configurable: true
  47354. });
  47355. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47356. get: function () {
  47357. return this._blurScale;
  47358. },
  47359. set: function (value) {
  47360. if (this._blurScale === value) {
  47361. return;
  47362. }
  47363. this._blurScale = value;
  47364. this._disposeBlurPostProcesses();
  47365. },
  47366. enumerable: true,
  47367. configurable: true
  47368. });
  47369. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47370. get: function () {
  47371. return this._blurKernel;
  47372. },
  47373. set: function (value) {
  47374. if (this._blurKernel === value) {
  47375. return;
  47376. }
  47377. this._blurKernel = value;
  47378. this._disposeBlurPostProcesses();
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47384. get: function () {
  47385. return this._useKernelBlur;
  47386. },
  47387. set: function (value) {
  47388. if (this._useKernelBlur === value) {
  47389. return;
  47390. }
  47391. this._useKernelBlur = value;
  47392. this._disposeBlurPostProcesses();
  47393. },
  47394. enumerable: true,
  47395. configurable: true
  47396. });
  47397. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47398. get: function () {
  47399. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47400. },
  47401. set: function (value) {
  47402. this._depthScale = value;
  47403. },
  47404. enumerable: true,
  47405. configurable: true
  47406. });
  47407. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47408. get: function () {
  47409. return this._filter;
  47410. },
  47411. set: function (value) {
  47412. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47413. if (this._light.needCube()) {
  47414. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47415. this.useExponentialShadowMap = true;
  47416. return;
  47417. }
  47418. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47419. this.useCloseExponentialShadowMap = true;
  47420. return;
  47421. }
  47422. }
  47423. if (this._filter === value) {
  47424. return;
  47425. }
  47426. this._filter = value;
  47427. this._disposeBlurPostProcesses();
  47428. this._applyFilterValues();
  47429. this._light._markMeshesAsLightDirty();
  47430. },
  47431. enumerable: true,
  47432. configurable: true
  47433. });
  47434. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47435. get: function () {
  47436. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47437. },
  47438. set: function (value) {
  47439. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47440. return;
  47441. }
  47442. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47443. },
  47444. enumerable: true,
  47445. configurable: true
  47446. });
  47447. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47448. get: function () {
  47449. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47450. return this.useExponentialShadowMap;
  47451. },
  47452. set: function (value) {
  47453. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47454. this.useExponentialShadowMap = value;
  47455. },
  47456. enumerable: true,
  47457. configurable: true
  47458. });
  47459. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47460. get: function () {
  47461. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47462. return this.useBlurExponentialShadowMap;
  47463. },
  47464. set: function (value) {
  47465. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47466. this.useBlurExponentialShadowMap = value;
  47467. },
  47468. enumerable: true,
  47469. configurable: true
  47470. });
  47471. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  47472. get: function () {
  47473. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  47474. },
  47475. set: function (value) {
  47476. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  47477. return;
  47478. }
  47479. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47480. },
  47481. enumerable: true,
  47482. configurable: true
  47483. });
  47484. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  47485. get: function () {
  47486. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  47487. },
  47488. set: function (value) {
  47489. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47490. return;
  47491. }
  47492. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47493. },
  47494. enumerable: true,
  47495. configurable: true
  47496. });
  47497. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  47498. get: function () {
  47499. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47500. },
  47501. set: function (value) {
  47502. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47503. return;
  47504. }
  47505. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47506. },
  47507. enumerable: true,
  47508. configurable: true
  47509. });
  47510. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47511. get: function () {
  47512. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47513. },
  47514. set: function (value) {
  47515. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47516. return;
  47517. }
  47518. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. /**
  47524. * Returns the darkness value (float).
  47525. */
  47526. ShadowGenerator.prototype.getDarkness = function () {
  47527. return this._darkness;
  47528. };
  47529. /**
  47530. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47531. * Returns the ShadowGenerator.
  47532. */
  47533. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47534. if (darkness >= 1.0)
  47535. this._darkness = 1.0;
  47536. else if (darkness <= 0.0)
  47537. this._darkness = 0.0;
  47538. else
  47539. this._darkness = darkness;
  47540. return this;
  47541. };
  47542. /**
  47543. * Sets the ability to have transparent shadow (boolean).
  47544. * Returns the ShadowGenerator.
  47545. */
  47546. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47547. this._transparencyShadow = hasShadow;
  47548. return this;
  47549. };
  47550. /**
  47551. * Returns a RenderTargetTexture object : the shadow map texture.
  47552. */
  47553. ShadowGenerator.prototype.getShadowMap = function () {
  47554. return this._shadowMap;
  47555. };
  47556. /**
  47557. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  47558. */
  47559. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  47560. if (this._shadowMap2) {
  47561. return this._shadowMap2;
  47562. }
  47563. return this._shadowMap;
  47564. };
  47565. /**
  47566. * Returns the associated light object.
  47567. */
  47568. ShadowGenerator.prototype.getLight = function () {
  47569. return this._light;
  47570. };
  47571. ShadowGenerator.prototype._initializeGenerator = function () {
  47572. this._light._markMeshesAsLightDirty();
  47573. this._initializeShadowMap();
  47574. };
  47575. ShadowGenerator.prototype._initializeShadowMap = function () {
  47576. var _this = this;
  47577. // Render target
  47578. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  47579. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47580. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47581. this._shadowMap.anisotropicFilteringLevel = 1;
  47582. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47583. this._shadowMap.renderParticles = false;
  47584. this._shadowMap.ignoreCameraViewport = true;
  47585. // Record Face Index before render.
  47586. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  47587. _this._currentFaceIndex = faceIndex;
  47588. });
  47589. // Custom render function.
  47590. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  47591. // Blur if required afer render.
  47592. this._shadowMap.onAfterUnbindObservable.add(function () {
  47593. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  47594. return;
  47595. }
  47596. if (!_this._blurPostProcesses) {
  47597. _this._initializeBlurRTTAndPostProcesses();
  47598. }
  47599. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  47600. });
  47601. // Clear according to the chosen filter.
  47602. this._shadowMap.onClearObservable.add(function (engine) {
  47603. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  47604. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  47605. }
  47606. else {
  47607. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47608. }
  47609. });
  47610. };
  47611. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  47612. var _this = this;
  47613. var engine = this._scene.getEngine();
  47614. var targetSize = this._mapSize / this.blurScale;
  47615. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  47616. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  47617. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47618. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47619. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47620. }
  47621. if (this.useKernelBlur) {
  47622. 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);
  47623. this._kernelBlurXPostprocess.width = targetSize;
  47624. this._kernelBlurXPostprocess.height = targetSize;
  47625. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  47626. effect.setTexture("textureSampler", _this._shadowMap);
  47627. });
  47628. 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);
  47629. this._kernelBlurXPostprocess.autoClear = false;
  47630. this._kernelBlurYPostprocess.autoClear = false;
  47631. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47632. this._kernelBlurXPostprocess.packedFloat = true;
  47633. this._kernelBlurYPostprocess.packedFloat = true;
  47634. }
  47635. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  47636. }
  47637. else {
  47638. 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);
  47639. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  47640. effect.setFloat2("screenSize", targetSize, targetSize);
  47641. effect.setTexture("textureSampler", _this._shadowMap);
  47642. });
  47643. this._boxBlurPostprocess.autoClear = false;
  47644. this._blurPostProcesses = [this._boxBlurPostprocess];
  47645. }
  47646. };
  47647. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  47648. var index;
  47649. var engine = this._scene.getEngine();
  47650. if (depthOnlySubMeshes.length) {
  47651. engine.setColorWrite(false);
  47652. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  47653. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  47654. }
  47655. engine.setColorWrite(true);
  47656. }
  47657. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47658. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47659. }
  47660. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47661. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47662. }
  47663. if (this._transparencyShadow) {
  47664. for (index = 0; index < transparentSubMeshes.length; index++) {
  47665. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47666. }
  47667. }
  47668. };
  47669. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47670. var _this = this;
  47671. var mesh = subMesh.getRenderingMesh();
  47672. var scene = this._scene;
  47673. var engine = scene.getEngine();
  47674. // Culling
  47675. engine.setState(subMesh.getMaterial().backFaceCulling);
  47676. // Managing instances
  47677. var batch = mesh._getInstancesRenderList(subMesh._id);
  47678. if (batch.mustReturn) {
  47679. return;
  47680. }
  47681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47682. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47683. engine.enableEffect(this._effect);
  47684. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47685. var material = subMesh.getMaterial();
  47686. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47687. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47688. this._effect.setVector3("lightPosition", this.getLight().position);
  47689. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47690. // Alpha test
  47691. if (material && material.needAlphaTesting()) {
  47692. var alphaTexture = material.getAlphaTestTexture();
  47693. if (alphaTexture) {
  47694. this._effect.setTexture("diffuseSampler", alphaTexture);
  47695. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47696. }
  47697. }
  47698. // Bones
  47699. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47700. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47701. }
  47702. if (this.forceBackFacesOnly) {
  47703. engine.setState(true, 0, false, true);
  47704. }
  47705. // Draw
  47706. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47707. if (this.forceBackFacesOnly) {
  47708. engine.setState(true, 0, false, false);
  47709. }
  47710. }
  47711. else {
  47712. // Need to reset refresh rate of the shadowMap
  47713. this._shadowMap.resetRefreshCounter();
  47714. }
  47715. };
  47716. ShadowGenerator.prototype._applyFilterValues = function () {
  47717. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47718. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47719. }
  47720. else {
  47721. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47722. }
  47723. };
  47724. /**
  47725. * Force shader compilation including textures ready check
  47726. */
  47727. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47728. var _this = this;
  47729. var scene = this._scene;
  47730. var engine = scene.getEngine();
  47731. var subMeshes = new Array();
  47732. var currentIndex = 0;
  47733. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47734. var mesh = _a[_i];
  47735. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47736. }
  47737. var checkReady = function () {
  47738. if (!_this._scene || !_this._scene.getEngine()) {
  47739. return;
  47740. }
  47741. var subMesh = subMeshes[currentIndex];
  47742. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47743. currentIndex++;
  47744. if (currentIndex >= subMeshes.length) {
  47745. if (onCompiled) {
  47746. onCompiled(_this);
  47747. }
  47748. return;
  47749. }
  47750. }
  47751. setTimeout(checkReady, 16);
  47752. };
  47753. if (subMeshes.length > 0) {
  47754. checkReady();
  47755. }
  47756. };
  47757. /**
  47758. * Boolean : true when the ShadowGenerator is finally computed.
  47759. */
  47760. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47761. var defines = [];
  47762. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47763. defines.push("#define FLOAT");
  47764. }
  47765. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47766. defines.push("#define ESM");
  47767. }
  47768. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47769. var mesh = subMesh.getMesh();
  47770. var material = subMesh.getMaterial();
  47771. // Alpha test
  47772. if (material && material.needAlphaTesting()) {
  47773. var alphaTexture = material.getAlphaTestTexture();
  47774. if (alphaTexture) {
  47775. defines.push("#define ALPHATEST");
  47776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47777. attribs.push(BABYLON.VertexBuffer.UVKind);
  47778. defines.push("#define UV1");
  47779. }
  47780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47781. if (alphaTexture.coordinatesIndex === 1) {
  47782. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47783. defines.push("#define UV2");
  47784. }
  47785. }
  47786. }
  47787. }
  47788. // Bones
  47789. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47790. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47791. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47792. if (mesh.numBoneInfluencers > 4) {
  47793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47795. }
  47796. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47797. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47798. }
  47799. else {
  47800. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47801. }
  47802. // Instances
  47803. if (useInstances) {
  47804. defines.push("#define INSTANCES");
  47805. attribs.push("world0");
  47806. attribs.push("world1");
  47807. attribs.push("world2");
  47808. attribs.push("world3");
  47809. }
  47810. // Get correct effect
  47811. var join = defines.join("\n");
  47812. if (this._cachedDefines !== join) {
  47813. this._cachedDefines = join;
  47814. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  47815. }
  47816. return this._effect.isReady();
  47817. };
  47818. /**
  47819. * This creates the defines related to the standard BJS materials.
  47820. */
  47821. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  47822. var scene = this._scene;
  47823. var light = this._light;
  47824. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47825. return;
  47826. }
  47827. defines["SHADOW" + lightIndex] = true;
  47828. if (this.usePoissonSampling) {
  47829. defines["SHADOWPCF" + lightIndex] = true;
  47830. }
  47831. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47832. defines["SHADOWESM" + lightIndex] = true;
  47833. }
  47834. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  47835. defines["SHADOWCLOSEESM" + lightIndex] = true;
  47836. }
  47837. if (light.needCube()) {
  47838. defines["SHADOWCUBE" + lightIndex] = true;
  47839. }
  47840. };
  47841. /**
  47842. * This binds shadow lights related to the standard BJS materials.
  47843. * It implies the unifroms available on the materials are the standard BJS ones.
  47844. */
  47845. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  47846. var light = this._light;
  47847. var scene = this._scene;
  47848. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47849. return;
  47850. }
  47851. if (!light.needCube()) {
  47852. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  47853. }
  47854. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  47855. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  47856. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  47857. };
  47858. // Methods
  47859. /**
  47860. * Returns a Matrix object : the updated transformation matrix.
  47861. */
  47862. ShadowGenerator.prototype.getTransformMatrix = function () {
  47863. var scene = this._scene;
  47864. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  47865. return this._transformMatrix;
  47866. }
  47867. this._currentRenderID = scene.getRenderId();
  47868. this._currentFaceIndexCache = this._currentFaceIndex;
  47869. var lightPosition = this._light.position;
  47870. if (this._light.computeTransformedInformation()) {
  47871. lightPosition = this._light.transformedPosition;
  47872. }
  47873. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  47874. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  47875. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  47876. }
  47877. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  47878. this._cachedPosition = lightPosition.clone();
  47879. this._cachedDirection = this._lightDirection.clone();
  47880. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  47881. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  47882. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  47883. }
  47884. return this._transformMatrix;
  47885. };
  47886. ShadowGenerator.prototype.recreateShadowMap = function () {
  47887. // Track render list.
  47888. var renderList = this._shadowMap.renderList;
  47889. // Clean up existing data.
  47890. this._disposeRTTandPostProcesses();
  47891. // Reinitializes.
  47892. this._initializeGenerator();
  47893. // Reaffect the filter to ensure a correct fallback if necessary.
  47894. this.filter = this.filter;
  47895. // Reaffect the filter.
  47896. this._applyFilterValues();
  47897. // Reaffect Render List.
  47898. this._shadowMap.renderList = renderList;
  47899. };
  47900. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  47901. if (this._shadowMap2) {
  47902. this._shadowMap2.dispose();
  47903. this._shadowMap2 = null;
  47904. }
  47905. if (this._downSamplePostprocess) {
  47906. this._downSamplePostprocess.dispose();
  47907. this._downSamplePostprocess = null;
  47908. }
  47909. if (this._boxBlurPostprocess) {
  47910. this._boxBlurPostprocess.dispose();
  47911. this._boxBlurPostprocess = null;
  47912. }
  47913. if (this._kernelBlurXPostprocess) {
  47914. this._kernelBlurXPostprocess.dispose();
  47915. this._kernelBlurXPostprocess = null;
  47916. }
  47917. if (this._kernelBlurYPostprocess) {
  47918. this._kernelBlurYPostprocess.dispose();
  47919. this._kernelBlurYPostprocess = null;
  47920. }
  47921. this._blurPostProcesses = null;
  47922. };
  47923. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  47924. if (this._shadowMap) {
  47925. this._shadowMap.dispose();
  47926. this._shadowMap = null;
  47927. }
  47928. this._disposeBlurPostProcesses();
  47929. };
  47930. /**
  47931. * Disposes the ShadowGenerator.
  47932. * Returns nothing.
  47933. */
  47934. ShadowGenerator.prototype.dispose = function () {
  47935. this._disposeRTTandPostProcesses();
  47936. this._light._shadowGenerator = null;
  47937. this._light._markMeshesAsLightDirty();
  47938. };
  47939. /**
  47940. * Serializes the ShadowGenerator and returns a serializationObject.
  47941. */
  47942. ShadowGenerator.prototype.serialize = function () {
  47943. var serializationObject = {};
  47944. var shadowMap = this.getShadowMap();
  47945. serializationObject.lightId = this._light.id;
  47946. serializationObject.mapSize = shadowMap.getRenderSize();
  47947. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  47948. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  47949. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47950. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47951. serializationObject.usePoissonSampling = this.usePoissonSampling;
  47952. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  47953. serializationObject.depthScale = this.depthScale;
  47954. serializationObject.darkness = this.getDarkness();
  47955. serializationObject.blurBoxOffset = this.blurBoxOffset;
  47956. serializationObject.blurKernel = this.blurKernel;
  47957. serializationObject.blurScale = this.blurScale;
  47958. serializationObject.useKernelBlur = this.useKernelBlur;
  47959. serializationObject.transparencyShadow = this._transparencyShadow;
  47960. serializationObject.renderList = [];
  47961. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  47962. var mesh = shadowMap.renderList[meshIndex];
  47963. serializationObject.renderList.push(mesh.id);
  47964. }
  47965. return serializationObject;
  47966. };
  47967. /**
  47968. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  47969. */
  47970. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  47971. //casting to point light, as light is missing the position attr and typescript complains.
  47972. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  47973. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  47974. var shadowMap = shadowGenerator.getShadowMap();
  47975. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  47976. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  47977. meshes.forEach(function (mesh) {
  47978. shadowMap.renderList.push(mesh);
  47979. });
  47980. }
  47981. if (parsedShadowGenerator.usePoissonSampling) {
  47982. shadowGenerator.usePoissonSampling = true;
  47983. }
  47984. else if (parsedShadowGenerator.useExponentialShadowMap) {
  47985. shadowGenerator.useExponentialShadowMap = true;
  47986. }
  47987. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47988. shadowGenerator.useBlurExponentialShadowMap = true;
  47989. }
  47990. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  47991. shadowGenerator.useCloseExponentialShadowMap = true;
  47992. }
  47993. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47994. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  47995. }
  47996. else if (parsedShadowGenerator.useVarianceShadowMap) {
  47997. shadowGenerator.useExponentialShadowMap = true;
  47998. }
  47999. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  48000. shadowGenerator.useBlurExponentialShadowMap = true;
  48001. }
  48002. if (parsedShadowGenerator.depthScale) {
  48003. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  48004. }
  48005. if (parsedShadowGenerator.blurScale) {
  48006. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  48007. }
  48008. if (parsedShadowGenerator.blurBoxOffset) {
  48009. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  48010. }
  48011. if (parsedShadowGenerator.useKernelBlur) {
  48012. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  48013. }
  48014. if (parsedShadowGenerator.blurKernel) {
  48015. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  48016. }
  48017. if (parsedShadowGenerator.bias !== undefined) {
  48018. shadowGenerator.bias = parsedShadowGenerator.bias;
  48019. }
  48020. if (parsedShadowGenerator.darkness) {
  48021. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  48022. }
  48023. if (parsedShadowGenerator.transparencyShadow) {
  48024. shadowGenerator.setTransparencyShadow(true);
  48025. }
  48026. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  48027. return shadowGenerator;
  48028. };
  48029. ShadowGenerator._FILTER_NONE = 0;
  48030. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  48031. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  48032. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  48033. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  48034. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  48035. return ShadowGenerator;
  48036. }());
  48037. BABYLON.ShadowGenerator = ShadowGenerator;
  48038. })(BABYLON || (BABYLON = {}));
  48039. //# sourceMappingURL=babylon.shadowGenerator.js.map
  48040. var BABYLON;
  48041. (function (BABYLON) {
  48042. var DefaultLoadingScreen = (function () {
  48043. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48044. if (_loadingText === void 0) { _loadingText = ""; }
  48045. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48046. var _this = this;
  48047. this._renderingCanvas = _renderingCanvas;
  48048. this._loadingText = _loadingText;
  48049. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48050. // Resize
  48051. this._resizeLoadingUI = function () {
  48052. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48053. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48054. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48055. _this._loadingDiv.style.left = canvasRect.left + "px";
  48056. _this._loadingDiv.style.top = canvasRect.top + "px";
  48057. _this._loadingDiv.style.width = canvasRect.width + "px";
  48058. _this._loadingDiv.style.height = canvasRect.height + "px";
  48059. };
  48060. }
  48061. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48062. if (this._loadingDiv) {
  48063. // Do not add a loading screen if there is already one
  48064. return;
  48065. }
  48066. this._loadingDiv = document.createElement("div");
  48067. this._loadingDiv.id = "babylonjsLoadingDiv";
  48068. this._loadingDiv.style.opacity = "0";
  48069. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48070. // Loading text
  48071. this._loadingTextDiv = document.createElement("div");
  48072. this._loadingTextDiv.style.position = "absolute";
  48073. this._loadingTextDiv.style.left = "0";
  48074. this._loadingTextDiv.style.top = "50%";
  48075. this._loadingTextDiv.style.marginTop = "80px";
  48076. this._loadingTextDiv.style.width = "100%";
  48077. this._loadingTextDiv.style.height = "20px";
  48078. this._loadingTextDiv.style.fontFamily = "Arial";
  48079. this._loadingTextDiv.style.fontSize = "14px";
  48080. this._loadingTextDiv.style.color = "white";
  48081. this._loadingTextDiv.style.textAlign = "center";
  48082. this._loadingTextDiv.innerHTML = "Loading";
  48083. this._loadingDiv.appendChild(this._loadingTextDiv);
  48084. //set the predefined text
  48085. this._loadingTextDiv.innerHTML = this._loadingText;
  48086. // Generating keyframes
  48087. var style = document.createElement('style');
  48088. style.type = 'text/css';
  48089. 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 }";
  48090. style.innerHTML = keyFrames;
  48091. document.getElementsByTagName('head')[0].appendChild(style);
  48092. // Loading img
  48093. var imgBack = new Image();
  48094. 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";
  48095. imgBack.style.position = "absolute";
  48096. imgBack.style.left = "50%";
  48097. imgBack.style.top = "50%";
  48098. imgBack.style.marginLeft = "-60px";
  48099. imgBack.style.marginTop = "-60px";
  48100. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48101. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48102. imgBack.style.transformOrigin = "50% 50%";
  48103. imgBack.style.webkitTransformOrigin = "50% 50%";
  48104. this._loadingDiv.appendChild(imgBack);
  48105. this._resizeLoadingUI();
  48106. window.addEventListener("resize", this._resizeLoadingUI);
  48107. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48108. document.body.appendChild(this._loadingDiv);
  48109. this._loadingDiv.style.opacity = "1";
  48110. };
  48111. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48112. var _this = this;
  48113. if (!this._loadingDiv) {
  48114. return;
  48115. }
  48116. var onTransitionEnd = function () {
  48117. if (!_this._loadingDiv) {
  48118. return;
  48119. }
  48120. document.body.removeChild(_this._loadingDiv);
  48121. window.removeEventListener("resize", _this._resizeLoadingUI);
  48122. _this._loadingDiv = null;
  48123. };
  48124. this._loadingDiv.style.opacity = "0";
  48125. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48126. };
  48127. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48128. set: function (text) {
  48129. this._loadingText = text;
  48130. if (this._loadingTextDiv) {
  48131. this._loadingTextDiv.innerHTML = this._loadingText;
  48132. }
  48133. },
  48134. enumerable: true,
  48135. configurable: true
  48136. });
  48137. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48138. get: function () {
  48139. return this._loadingDivBackgroundColor;
  48140. },
  48141. set: function (color) {
  48142. this._loadingDivBackgroundColor = color;
  48143. if (!this._loadingDiv) {
  48144. return;
  48145. }
  48146. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48147. },
  48148. enumerable: true,
  48149. configurable: true
  48150. });
  48151. return DefaultLoadingScreen;
  48152. }());
  48153. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48154. })(BABYLON || (BABYLON = {}));
  48155. //# sourceMappingURL=babylon.loadingScreen.js.map
  48156. var BABYLON;
  48157. (function (BABYLON) {
  48158. var SceneLoader = (function () {
  48159. function SceneLoader() {
  48160. }
  48161. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48162. get: function () {
  48163. return 0;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48169. get: function () {
  48170. return 1;
  48171. },
  48172. enumerable: true,
  48173. configurable: true
  48174. });
  48175. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48176. get: function () {
  48177. return 2;
  48178. },
  48179. enumerable: true,
  48180. configurable: true
  48181. });
  48182. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48183. get: function () {
  48184. return 3;
  48185. },
  48186. enumerable: true,
  48187. configurable: true
  48188. });
  48189. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48190. get: function () {
  48191. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48192. },
  48193. set: function (value) {
  48194. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48195. },
  48196. enumerable: true,
  48197. configurable: true
  48198. });
  48199. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48200. get: function () {
  48201. return SceneLoader._ShowLoadingScreen;
  48202. },
  48203. set: function (value) {
  48204. SceneLoader._ShowLoadingScreen = value;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. Object.defineProperty(SceneLoader, "loggingLevel", {
  48210. get: function () {
  48211. return SceneLoader._loggingLevel;
  48212. },
  48213. set: function (value) {
  48214. SceneLoader._loggingLevel = value;
  48215. },
  48216. enumerable: true,
  48217. configurable: true
  48218. });
  48219. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48220. get: function () {
  48221. return SceneLoader._CleanBoneMatrixWeights;
  48222. },
  48223. set: function (value) {
  48224. SceneLoader._CleanBoneMatrixWeights = value;
  48225. },
  48226. enumerable: true,
  48227. configurable: true
  48228. });
  48229. SceneLoader._getDefaultPlugin = function () {
  48230. return SceneLoader._registeredPlugins[".babylon"];
  48231. };
  48232. SceneLoader._getPluginForExtension = function (extension) {
  48233. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48234. if (registeredPlugin) {
  48235. return registeredPlugin;
  48236. }
  48237. return SceneLoader._getDefaultPlugin();
  48238. };
  48239. SceneLoader._getPluginForDirectLoad = function (data) {
  48240. for (var extension in SceneLoader._registeredPlugins) {
  48241. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48242. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48243. return SceneLoader._registeredPlugins[extension];
  48244. }
  48245. }
  48246. return SceneLoader._getDefaultPlugin();
  48247. };
  48248. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48249. if (sceneFilename.name) {
  48250. sceneFilename = sceneFilename.name;
  48251. }
  48252. var dotPosition = sceneFilename.lastIndexOf(".");
  48253. var queryStringPosition = sceneFilename.indexOf("?");
  48254. if (queryStringPosition === -1) {
  48255. queryStringPosition = sceneFilename.length;
  48256. }
  48257. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48258. return SceneLoader._getPluginForExtension(extension);
  48259. };
  48260. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48261. SceneLoader._getDirectLoad = function (sceneFilename) {
  48262. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48263. return sceneFilename.substr(5);
  48264. }
  48265. return null;
  48266. };
  48267. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48268. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48269. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48270. var plugin = registeredPlugin.plugin;
  48271. var useArrayBuffer = registeredPlugin.isBinary;
  48272. var database;
  48273. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48274. var dataCallback = function (data) {
  48275. if (scene.isDisposed) {
  48276. onError("Scene has been disposed");
  48277. return;
  48278. }
  48279. scene.database = database;
  48280. try {
  48281. onSuccess(plugin, data);
  48282. }
  48283. catch (e) {
  48284. onError(null, e);
  48285. }
  48286. };
  48287. var manifestChecked = function (success) {
  48288. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48289. onError(request.status + " " + request.statusText);
  48290. });
  48291. };
  48292. if (directLoad) {
  48293. dataCallback(directLoad);
  48294. return;
  48295. }
  48296. if (rootUrl.indexOf("file:") === -1) {
  48297. if (scene.getEngine().enableOfflineSupport) {
  48298. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48299. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48300. }
  48301. else {
  48302. manifestChecked(true);
  48303. }
  48304. }
  48305. else {
  48306. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48307. }
  48308. };
  48309. // Public functions
  48310. SceneLoader.GetPluginForExtension = function (extension) {
  48311. return SceneLoader._getPluginForExtension(extension).plugin;
  48312. };
  48313. SceneLoader.RegisterPlugin = function (plugin) {
  48314. if (typeof plugin.extensions === "string") {
  48315. var extension = plugin.extensions;
  48316. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48317. plugin: plugin,
  48318. isBinary: false
  48319. };
  48320. }
  48321. else {
  48322. var extensions = plugin.extensions;
  48323. Object.keys(extensions).forEach(function (extension) {
  48324. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48325. plugin: plugin,
  48326. isBinary: extensions[extension].isBinary
  48327. };
  48328. });
  48329. }
  48330. };
  48331. /**
  48332. * Import meshes into a scene
  48333. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48334. * @param rootUrl a string that defines the root url for scene and resources
  48335. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48336. * @param scene the instance of BABYLON.Scene to append to
  48337. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48338. * @param onProgress a callback with a progress event for each file being loaded
  48339. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48340. */
  48341. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48342. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48343. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48344. return;
  48345. }
  48346. var loadingToken = {};
  48347. scene._addPendingData(loadingToken);
  48348. var errorHandler = function (message, exception) {
  48349. if (onError) {
  48350. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48351. }
  48352. scene._removePendingData(loadingToken);
  48353. };
  48354. var progressHandler = function (event) {
  48355. if (onProgress) {
  48356. onProgress(event);
  48357. }
  48358. };
  48359. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48360. if (plugin.importMesh) {
  48361. var syncedPlugin = plugin;
  48362. var meshes = [];
  48363. var particleSystems = [];
  48364. var skeletons = [];
  48365. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48366. return;
  48367. }
  48368. if (onSuccess) {
  48369. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48370. onSuccess(meshes, particleSystems, skeletons);
  48371. scene._removePendingData(loadingToken);
  48372. }
  48373. }
  48374. else {
  48375. var asyncedPlugin = plugin;
  48376. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48377. if (onSuccess) {
  48378. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48379. onSuccess(meshes, particleSystems, skeletons);
  48380. scene._removePendingData(loadingToken);
  48381. }
  48382. }, progressHandler, errorHandler);
  48383. }
  48384. }, progressHandler, errorHandler);
  48385. };
  48386. /**
  48387. * Load a scene
  48388. * @param rootUrl a string that defines the root url for scene and resources
  48389. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48390. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48391. * @param onSuccess a callback with the scene when import succeeds
  48392. * @param onProgress a callback with a progress event for each file being loaded
  48393. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48394. */
  48395. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48396. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48397. };
  48398. /**
  48399. * Append a scene
  48400. * @param rootUrl a string that defines the root url for scene and resources
  48401. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48402. * @param scene is the instance of BABYLON.Scene to append to
  48403. * @param onSuccess a callback with the scene when import succeeds
  48404. * @param onProgress a callback with a progress event for each file being loaded
  48405. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48406. */
  48407. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48408. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48409. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48410. return;
  48411. }
  48412. if (SceneLoader.ShowLoadingScreen) {
  48413. scene.getEngine().displayLoadingUI();
  48414. }
  48415. var loadingToken = {};
  48416. scene._addPendingData(loadingToken);
  48417. var errorHandler = function (message, exception) {
  48418. if (onError) {
  48419. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48420. }
  48421. scene._removePendingData(loadingToken);
  48422. scene.getEngine().hideLoadingUI();
  48423. };
  48424. var progressHandler = function (event) {
  48425. if (onProgress) {
  48426. onProgress(event);
  48427. }
  48428. };
  48429. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48430. if (plugin.load) {
  48431. var syncedPlugin = plugin;
  48432. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48433. return;
  48434. }
  48435. if (onSuccess) {
  48436. onSuccess(scene);
  48437. }
  48438. scene.loadingPluginName = plugin.name;
  48439. scene._removePendingData(loadingToken);
  48440. }
  48441. else {
  48442. var asyncedPlugin = plugin;
  48443. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48444. if (onSuccess) {
  48445. onSuccess(scene);
  48446. }
  48447. scene.loadingPluginName = plugin.name;
  48448. scene._removePendingData(loadingToken);
  48449. }, progressHandler, errorHandler);
  48450. }
  48451. if (SceneLoader.ShowLoadingScreen) {
  48452. scene.executeWhenReady(function () {
  48453. scene.getEngine().hideLoadingUI();
  48454. });
  48455. }
  48456. }, progressHandler, errorHandler);
  48457. };
  48458. // Flags
  48459. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48460. SceneLoader._ShowLoadingScreen = true;
  48461. SceneLoader._CleanBoneMatrixWeights = false;
  48462. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48463. // Members
  48464. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48465. SceneLoader._registeredPlugins = {};
  48466. return SceneLoader;
  48467. }());
  48468. BABYLON.SceneLoader = SceneLoader;
  48469. ;
  48470. })(BABYLON || (BABYLON = {}));
  48471. //# sourceMappingURL=babylon.sceneLoader.js.map
  48472. var BABYLON;
  48473. (function (BABYLON) {
  48474. var Internals;
  48475. (function (Internals) {
  48476. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48477. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48478. var parsedMaterial = parsedData.materials[index];
  48479. if (parsedMaterial.id === id) {
  48480. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48481. }
  48482. }
  48483. return null;
  48484. };
  48485. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48486. for (var i in names) {
  48487. if (mesh.name === names[i]) {
  48488. hierarchyIds.push(mesh.id);
  48489. return true;
  48490. }
  48491. }
  48492. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48493. hierarchyIds.push(mesh.id);
  48494. return true;
  48495. }
  48496. return false;
  48497. };
  48498. var logOperation = function (operation, producer) {
  48499. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48500. };
  48501. BABYLON.SceneLoader.RegisterPlugin({
  48502. name: "babylon.js",
  48503. extensions: ".babylon",
  48504. canDirectLoad: function (data) {
  48505. if (data.indexOf("babylon") !== -1) {
  48506. return true;
  48507. }
  48508. return false;
  48509. },
  48510. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48511. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48512. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48513. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48514. // and avoid problems with multiple concurrent .babylon loads.
  48515. var log = "importMesh has failed JSON parse";
  48516. try {
  48517. var parsedData = JSON.parse(data);
  48518. log = "";
  48519. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48520. if (!meshesNames) {
  48521. meshesNames = null;
  48522. }
  48523. else if (!Array.isArray(meshesNames)) {
  48524. meshesNames = [meshesNames];
  48525. }
  48526. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48527. var loadedSkeletonsIds = [];
  48528. var loadedMaterialsIds = [];
  48529. var hierarchyIds = [];
  48530. var index;
  48531. var cache;
  48532. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48533. var parsedMesh = parsedData.meshes[index];
  48534. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48535. if (meshesNames !== null) {
  48536. // Remove found mesh name from list.
  48537. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48538. }
  48539. //Geometry?
  48540. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48541. //does the file contain geometries?
  48542. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48543. //find the correct geometry and add it to the scene
  48544. var found = false;
  48545. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48546. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48547. return;
  48548. }
  48549. else {
  48550. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48551. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48552. switch (geometryType) {
  48553. case "boxes":
  48554. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48555. break;
  48556. case "spheres":
  48557. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48558. break;
  48559. case "cylinders":
  48560. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48561. break;
  48562. case "toruses":
  48563. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48564. break;
  48565. case "grounds":
  48566. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48567. break;
  48568. case "planes":
  48569. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48570. break;
  48571. case "torusKnots":
  48572. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48573. break;
  48574. case "vertexData":
  48575. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48576. break;
  48577. }
  48578. found = true;
  48579. }
  48580. });
  48581. }
  48582. });
  48583. if (found === false) {
  48584. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48585. }
  48586. }
  48587. }
  48588. // Material ?
  48589. if (parsedMesh.materialId) {
  48590. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48591. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48592. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48593. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48594. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48595. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48596. var subMatId = parsedMultiMaterial.materials[matIndex];
  48597. loadedMaterialsIds.push(subMatId);
  48598. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48599. log += "\n\tMaterial " + mat.toString(fullDetails);
  48600. }
  48601. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48602. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48603. materialFound = true;
  48604. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48605. break;
  48606. }
  48607. }
  48608. }
  48609. if (materialFound === false) {
  48610. loadedMaterialsIds.push(parsedMesh.materialId);
  48611. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48612. if (!mat) {
  48613. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48614. }
  48615. else {
  48616. log += "\n\tMaterial " + mat.toString(fullDetails);
  48617. }
  48618. }
  48619. }
  48620. // Skeleton ?
  48621. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48622. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48623. if (skeletonAlreadyLoaded === false) {
  48624. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48625. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48626. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48627. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48628. skeletons.push(skeleton);
  48629. loadedSkeletonsIds.push(parsedSkeleton.id);
  48630. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48631. }
  48632. }
  48633. }
  48634. }
  48635. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48636. meshes.push(mesh);
  48637. log += "\n\tMesh " + mesh.toString(fullDetails);
  48638. }
  48639. }
  48640. // Connecting parents
  48641. var currentMesh;
  48642. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48643. currentMesh = scene.meshes[index];
  48644. if (currentMesh._waitingParentId) {
  48645. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48646. currentMesh._waitingParentId = undefined;
  48647. }
  48648. }
  48649. // freeze and compute world matrix application
  48650. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48651. currentMesh = scene.meshes[index];
  48652. if (currentMesh._waitingFreezeWorldMatrix) {
  48653. currentMesh.freezeWorldMatrix();
  48654. currentMesh._waitingFreezeWorldMatrix = undefined;
  48655. }
  48656. else {
  48657. currentMesh.computeWorldMatrix(true);
  48658. }
  48659. }
  48660. }
  48661. // Particles
  48662. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48663. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48664. var parsedParticleSystem = parsedData.particleSystems[index];
  48665. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48666. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48667. }
  48668. }
  48669. }
  48670. return true;
  48671. }
  48672. catch (err) {
  48673. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48674. log = null;
  48675. throw err;
  48676. }
  48677. finally {
  48678. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48679. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48680. }
  48681. }
  48682. },
  48683. load: function (scene, data, rootUrl) {
  48684. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48685. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48686. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48687. // and avoid problems with multiple concurrent .babylon loads.
  48688. var log = "importScene has failed JSON parse";
  48689. try {
  48690. var parsedData = JSON.parse(data);
  48691. log = "";
  48692. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48693. // Scene
  48694. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48695. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48696. }
  48697. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48698. scene.autoClear = parsedData.autoClear;
  48699. }
  48700. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48701. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48702. }
  48703. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48704. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48705. }
  48706. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48707. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48708. }
  48709. // Fog
  48710. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48711. scene.fogMode = parsedData.fogMode;
  48712. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48713. scene.fogStart = parsedData.fogStart;
  48714. scene.fogEnd = parsedData.fogEnd;
  48715. scene.fogDensity = parsedData.fogDensity;
  48716. log += "\tFog mode for scene: ";
  48717. switch (scene.fogMode) {
  48718. // getters not compiling, so using hardcoded
  48719. case 1:
  48720. log += "exp\n";
  48721. break;
  48722. case 2:
  48723. log += "exp2\n";
  48724. break;
  48725. case 3:
  48726. log += "linear\n";
  48727. break;
  48728. }
  48729. }
  48730. //Physics
  48731. if (parsedData.physicsEnabled) {
  48732. var physicsPlugin;
  48733. if (parsedData.physicsEngine === "cannon") {
  48734. physicsPlugin = new BABYLON.CannonJSPlugin();
  48735. }
  48736. else if (parsedData.physicsEngine === "oimo") {
  48737. physicsPlugin = new BABYLON.OimoJSPlugin();
  48738. }
  48739. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48740. //else - default engine, which is currently oimo
  48741. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48742. scene.enablePhysics(physicsGravity, physicsPlugin);
  48743. }
  48744. // Metadata
  48745. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48746. scene.metadata = parsedData.metadata;
  48747. }
  48748. //collisions, if defined. otherwise, default is true
  48749. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48750. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48751. }
  48752. scene.workerCollisions = !!parsedData.workerCollisions;
  48753. var index;
  48754. var cache;
  48755. // Lights
  48756. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48757. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48758. var parsedLight = parsedData.lights[index];
  48759. var light = BABYLON.Light.Parse(parsedLight, scene);
  48760. log += (index === 0 ? "\n\tLights:" : "");
  48761. log += "\n\t\t" + light.toString(fullDetails);
  48762. }
  48763. }
  48764. // Animations
  48765. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48766. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48767. var parsedAnimation = parsedData.animations[index];
  48768. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48769. scene.animations.push(animation);
  48770. log += (index === 0 ? "\n\tAnimations:" : "");
  48771. log += "\n\t\t" + animation.toString(fullDetails);
  48772. }
  48773. }
  48774. if (parsedData.autoAnimate) {
  48775. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48776. }
  48777. // Materials
  48778. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48779. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48780. var parsedMaterial = parsedData.materials[index];
  48781. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48782. log += (index === 0 ? "\n\tMaterials:" : "");
  48783. log += "\n\t\t" + mat.toString(fullDetails);
  48784. }
  48785. }
  48786. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48787. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48788. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48789. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48790. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48791. log += "\n\t\t" + mmat.toString(fullDetails);
  48792. }
  48793. }
  48794. // Morph targets
  48795. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48796. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  48797. var managerData = _a[_i];
  48798. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  48799. }
  48800. }
  48801. // Skeletons
  48802. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48803. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  48804. var parsedSkeleton = parsedData.skeletons[index];
  48805. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48806. log += (index === 0 ? "\n\tSkeletons:" : "");
  48807. log += "\n\t\t" + skeleton.toString(fullDetails);
  48808. }
  48809. }
  48810. // Geometries
  48811. var geometries = parsedData.geometries;
  48812. if (geometries !== undefined && geometries !== null) {
  48813. // Boxes
  48814. var boxes = geometries.boxes;
  48815. if (boxes !== undefined && boxes !== null) {
  48816. for (index = 0, cache = boxes.length; index < cache; index++) {
  48817. var parsedBox = boxes[index];
  48818. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48819. }
  48820. }
  48821. // Spheres
  48822. var spheres = geometries.spheres;
  48823. if (spheres !== undefined && spheres !== null) {
  48824. for (index = 0, cache = spheres.length; index < cache; index++) {
  48825. var parsedSphere = spheres[index];
  48826. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48827. }
  48828. }
  48829. // Cylinders
  48830. var cylinders = geometries.cylinders;
  48831. if (cylinders !== undefined && cylinders !== null) {
  48832. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48833. var parsedCylinder = cylinders[index];
  48834. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48835. }
  48836. }
  48837. // Toruses
  48838. var toruses = geometries.toruses;
  48839. if (toruses !== undefined && toruses !== null) {
  48840. for (index = 0, cache = toruses.length; index < cache; index++) {
  48841. var parsedTorus = toruses[index];
  48842. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48843. }
  48844. }
  48845. // Grounds
  48846. var grounds = geometries.grounds;
  48847. if (grounds !== undefined && grounds !== null) {
  48848. for (index = 0, cache = grounds.length; index < cache; index++) {
  48849. var parsedGround = grounds[index];
  48850. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48851. }
  48852. }
  48853. // Planes
  48854. var planes = geometries.planes;
  48855. if (planes !== undefined && planes !== null) {
  48856. for (index = 0, cache = planes.length; index < cache; index++) {
  48857. var parsedPlane = planes[index];
  48858. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48859. }
  48860. }
  48861. // TorusKnots
  48862. var torusKnots = geometries.torusKnots;
  48863. if (torusKnots !== undefined && torusKnots !== null) {
  48864. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48865. var parsedTorusKnot = torusKnots[index];
  48866. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48867. }
  48868. }
  48869. // VertexData
  48870. var vertexData = geometries.vertexData;
  48871. if (vertexData !== undefined && vertexData !== null) {
  48872. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48873. var parsedVertexData = vertexData[index];
  48874. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48875. }
  48876. }
  48877. }
  48878. // Meshes
  48879. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48880. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48881. var parsedMesh = parsedData.meshes[index];
  48882. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48883. log += (index === 0 ? "\n\tMeshes:" : "");
  48884. log += "\n\t\t" + mesh.toString(fullDetails);
  48885. }
  48886. }
  48887. // Cameras
  48888. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  48889. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48890. var parsedCamera = parsedData.cameras[index];
  48891. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48892. log += (index === 0 ? "\n\tCameras:" : "");
  48893. log += "\n\t\t" + camera.toString(fullDetails);
  48894. }
  48895. }
  48896. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  48897. scene.setActiveCameraByID(parsedData.activeCameraID);
  48898. }
  48899. // Browsing all the graph to connect the dots
  48900. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48901. var camera = scene.cameras[index];
  48902. if (camera._waitingParentId) {
  48903. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48904. camera._waitingParentId = undefined;
  48905. }
  48906. }
  48907. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48908. var light = scene.lights[index];
  48909. if (light._waitingParentId) {
  48910. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48911. light._waitingParentId = undefined;
  48912. }
  48913. }
  48914. // Sounds
  48915. var loadedSounds = [];
  48916. var loadedSound;
  48917. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  48918. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48919. var parsedSound = parsedData.sounds[index];
  48920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48921. if (!parsedSound.url)
  48922. parsedSound.url = parsedSound.name;
  48923. if (!loadedSounds[parsedSound.url]) {
  48924. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48925. loadedSounds[parsedSound.url] = loadedSound;
  48926. }
  48927. else {
  48928. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48929. }
  48930. }
  48931. else {
  48932. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48933. }
  48934. }
  48935. }
  48936. loadedSounds = [];
  48937. // Connect parents & children and parse actions
  48938. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48939. var mesh = scene.meshes[index];
  48940. if (mesh._waitingParentId) {
  48941. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48942. mesh._waitingParentId = undefined;
  48943. }
  48944. if (mesh._waitingActions) {
  48945. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48946. mesh._waitingActions = undefined;
  48947. }
  48948. }
  48949. // freeze world matrix application
  48950. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48951. var currentMesh = scene.meshes[index];
  48952. if (currentMesh._waitingFreezeWorldMatrix) {
  48953. currentMesh.freezeWorldMatrix();
  48954. currentMesh._waitingFreezeWorldMatrix = undefined;
  48955. }
  48956. else {
  48957. currentMesh.computeWorldMatrix(true);
  48958. }
  48959. }
  48960. // Particles Systems
  48961. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48962. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48963. var parsedParticleSystem = parsedData.particleSystems[index];
  48964. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48965. }
  48966. }
  48967. // Lens flares
  48968. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  48969. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48970. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48971. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48972. }
  48973. }
  48974. // Shadows
  48975. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  48976. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48977. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48978. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48979. }
  48980. }
  48981. // Lights exclusions / inclusions
  48982. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48983. var light = scene.lights[index];
  48984. // Excluded check
  48985. if (light._excludedMeshesIds.length > 0) {
  48986. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48987. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48988. if (excludedMesh) {
  48989. light.excludedMeshes.push(excludedMesh);
  48990. }
  48991. }
  48992. light._excludedMeshesIds = [];
  48993. }
  48994. // Included check
  48995. if (light._includedOnlyMeshesIds.length > 0) {
  48996. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48997. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48998. if (includedOnlyMesh) {
  48999. light.includedOnlyMeshes.push(includedOnlyMesh);
  49000. }
  49001. }
  49002. light._includedOnlyMeshesIds = [];
  49003. }
  49004. }
  49005. // Actions (scene)
  49006. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49007. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49008. }
  49009. // Finish
  49010. return true;
  49011. }
  49012. catch (err) {
  49013. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49014. log = null;
  49015. throw err;
  49016. }
  49017. finally {
  49018. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49019. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49020. }
  49021. }
  49022. }
  49023. });
  49024. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49025. })(BABYLON || (BABYLON = {}));
  49026. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49027. var BABYLON;
  49028. (function (BABYLON) {
  49029. var FilesInput = (function () {
  49030. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49031. this.onProcessFileCallback = function () { return true; };
  49032. this._engine = engine;
  49033. this._currentScene = scene;
  49034. this._sceneLoadedCallback = sceneLoadedCallback;
  49035. this._progressCallback = progressCallback;
  49036. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49037. this._textureLoadingCallback = textureLoadingCallback;
  49038. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49039. this._onReloadCallback = onReloadCallback;
  49040. }
  49041. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49042. var _this = this;
  49043. if (elementToMonitor) {
  49044. this._elementToMonitor = elementToMonitor;
  49045. this._dragEnterHandler = function (e) { _this.drag(e); };
  49046. this._dragOverHandler = function (e) { _this.drag(e); };
  49047. this._dropHandler = function (e) { _this.drop(e); };
  49048. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49049. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49050. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49051. }
  49052. };
  49053. FilesInput.prototype.dispose = function () {
  49054. if (!this._elementToMonitor) {
  49055. return;
  49056. }
  49057. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49058. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49059. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49060. };
  49061. FilesInput.prototype.renderFunction = function () {
  49062. if (this._additionalRenderLoopLogicCallback) {
  49063. this._additionalRenderLoopLogicCallback();
  49064. }
  49065. if (this._currentScene) {
  49066. if (this._textureLoadingCallback) {
  49067. var remaining = this._currentScene.getWaitingItemsCount();
  49068. if (remaining > 0) {
  49069. this._textureLoadingCallback(remaining);
  49070. }
  49071. }
  49072. this._currentScene.render();
  49073. }
  49074. };
  49075. FilesInput.prototype.drag = function (e) {
  49076. e.stopPropagation();
  49077. e.preventDefault();
  49078. };
  49079. FilesInput.prototype.drop = function (eventDrop) {
  49080. eventDrop.stopPropagation();
  49081. eventDrop.preventDefault();
  49082. this.loadFiles(eventDrop);
  49083. };
  49084. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49085. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49086. reader.readEntries(function (fileEntries) {
  49087. var remaining = fileEntries.length;
  49088. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49089. var fileEntry = fileEntries_1[_i];
  49090. if (fileEntry.isFile) {
  49091. fileEntry.file(function (file) {
  49092. file.correctName = relativePath + file.name;
  49093. files.push(file);
  49094. remaining--;
  49095. if (remaining === 0) {
  49096. callback();
  49097. }
  49098. });
  49099. }
  49100. else {
  49101. remaining--;
  49102. if (remaining === 0) {
  49103. callback();
  49104. }
  49105. }
  49106. }
  49107. });
  49108. };
  49109. FilesInput.prototype._processFiles = function (files) {
  49110. var skippedFiles = 0;
  49111. for (var i = 0; i < files.length; i++) {
  49112. var name = files[i].correctName.toLowerCase();
  49113. var extension = name.split('.').pop();
  49114. if (!this.onProcessFileCallback(files[i], name, extension)) {
  49115. skippedFiles++;
  49116. continue;
  49117. }
  49118. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49119. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49120. this._sceneFileToLoad = files[i];
  49121. }
  49122. else {
  49123. FilesInput.FilesToLoad[name] = files[i];
  49124. }
  49125. }
  49126. if (this._onReloadCallback) {
  49127. this._onReloadCallback(this._sceneFileToLoad);
  49128. }
  49129. else if (skippedFiles < files.length) {
  49130. this.reload();
  49131. }
  49132. };
  49133. FilesInput.prototype.loadFiles = function (event) {
  49134. var _this = this;
  49135. if (this._startingProcessingFilesCallback)
  49136. this._startingProcessingFilesCallback();
  49137. // Handling data transfer via drag'n'drop
  49138. if (event && event.dataTransfer && event.dataTransfer.files) {
  49139. this._filesToLoad = event.dataTransfer.files;
  49140. }
  49141. // Handling files from input files
  49142. if (event && event.target && event.target.files) {
  49143. this._filesToLoad = event.target.files;
  49144. }
  49145. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49146. var files_1 = [];
  49147. var folders = [];
  49148. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49149. for (var i = 0; i < this._filesToLoad.length; i++) {
  49150. var fileToLoad = this._filesToLoad[i];
  49151. var name_1 = fileToLoad.name.toLowerCase();
  49152. var type = fileToLoad.type;
  49153. var entry = void 0;
  49154. fileToLoad.correctName = name_1;
  49155. if (items) {
  49156. var item = items[i];
  49157. if (item.getAsEntry) {
  49158. entry = item.getAsEntry();
  49159. }
  49160. else if (item.webkitGetAsEntry) {
  49161. entry = item.webkitGetAsEntry();
  49162. }
  49163. }
  49164. if (!entry) {
  49165. files_1.push(fileToLoad);
  49166. }
  49167. else {
  49168. if (entry.isDirectory) {
  49169. folders.push(entry);
  49170. }
  49171. else {
  49172. files_1.push(fileToLoad);
  49173. }
  49174. }
  49175. }
  49176. if (folders.length === 0) {
  49177. this._processFiles(files_1);
  49178. }
  49179. else {
  49180. var remaining = folders.length;
  49181. // Extract folder content
  49182. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49183. var folder = folders_1[_i];
  49184. this._handleFolderDrop(folder, files_1, function () {
  49185. remaining--;
  49186. if (remaining === 0) {
  49187. _this._processFiles(files_1);
  49188. }
  49189. });
  49190. }
  49191. }
  49192. }
  49193. };
  49194. FilesInput.prototype.reload = function () {
  49195. var _this = this;
  49196. // If a ".babylon" file has been provided
  49197. if (this._sceneFileToLoad) {
  49198. if (this._currentScene) {
  49199. if (BABYLON.Tools.errorsCount > 0) {
  49200. BABYLON.Tools.ClearLogCache();
  49201. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49202. }
  49203. this._engine.stopRenderLoop();
  49204. this._currentScene.dispose();
  49205. }
  49206. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49207. _this._currentScene = newScene;
  49208. if (_this._sceneLoadedCallback) {
  49209. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49210. }
  49211. // Wait for textures and shaders to be ready
  49212. _this._currentScene.executeWhenReady(function () {
  49213. _this._engine.runRenderLoop(function () {
  49214. _this.renderFunction();
  49215. });
  49216. });
  49217. }, function (progress) {
  49218. if (_this._progressCallback) {
  49219. _this._progressCallback(progress);
  49220. }
  49221. });
  49222. }
  49223. else {
  49224. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49225. }
  49226. };
  49227. FilesInput.FilesToLoad = new Array();
  49228. return FilesInput;
  49229. }());
  49230. BABYLON.FilesInput = FilesInput;
  49231. })(BABYLON || (BABYLON = {}));
  49232. //# sourceMappingURL=babylon.filesInput.js.map
  49233. var BABYLON;
  49234. (function (BABYLON) {
  49235. /**
  49236. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49237. * The underlying implementation relies on an associative array to ensure the best performances.
  49238. * The value can be anything including 'null' but except 'undefined'
  49239. */
  49240. var StringDictionary = (function () {
  49241. function StringDictionary() {
  49242. this._count = 0;
  49243. this._data = {};
  49244. }
  49245. /**
  49246. * This will clear this dictionary and copy the content from the 'source' one.
  49247. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49248. * @param source the dictionary to take the content from and copy to this dictionary
  49249. */
  49250. StringDictionary.prototype.copyFrom = function (source) {
  49251. var _this = this;
  49252. this.clear();
  49253. source.forEach(function (t, v) { return _this.add(t, v); });
  49254. };
  49255. /**
  49256. * Get a value based from its key
  49257. * @param key the given key to get the matching value from
  49258. * @return the value if found, otherwise undefined is returned
  49259. */
  49260. StringDictionary.prototype.get = function (key) {
  49261. var val = this._data[key];
  49262. if (val !== undefined) {
  49263. return val;
  49264. }
  49265. return undefined;
  49266. };
  49267. /**
  49268. * Get a value from its key or add it if it doesn't exist.
  49269. * This method will ensure you that a given key/data will be present in the dictionary.
  49270. * @param key the given key to get the matching value from
  49271. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49272. * The factory will only be invoked if there's no data for the given key.
  49273. * @return the value corresponding to the key.
  49274. */
  49275. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49276. var val = this.get(key);
  49277. if (val !== undefined) {
  49278. return val;
  49279. }
  49280. val = factory(key);
  49281. if (val) {
  49282. this.add(key, val);
  49283. }
  49284. return val;
  49285. };
  49286. /**
  49287. * Get a value from its key if present in the dictionary otherwise add it
  49288. * @param key the key to get the value from
  49289. * @param val if there's no such key/value pair in the dictionary add it with this value
  49290. * @return the value corresponding to the key
  49291. */
  49292. StringDictionary.prototype.getOrAdd = function (key, val) {
  49293. var curVal = this.get(key);
  49294. if (curVal !== undefined) {
  49295. return curVal;
  49296. }
  49297. this.add(key, val);
  49298. return val;
  49299. };
  49300. /**
  49301. * Check if there's a given key in the dictionary
  49302. * @param key the key to check for
  49303. * @return true if the key is present, false otherwise
  49304. */
  49305. StringDictionary.prototype.contains = function (key) {
  49306. return this._data[key] !== undefined;
  49307. };
  49308. /**
  49309. * Add a new key and its corresponding value
  49310. * @param key the key to add
  49311. * @param value the value corresponding to the key
  49312. * @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
  49313. */
  49314. StringDictionary.prototype.add = function (key, value) {
  49315. if (this._data[key] !== undefined) {
  49316. return false;
  49317. }
  49318. this._data[key] = value;
  49319. ++this._count;
  49320. return true;
  49321. };
  49322. StringDictionary.prototype.set = function (key, value) {
  49323. if (this._data[key] === undefined) {
  49324. return false;
  49325. }
  49326. this._data[key] = value;
  49327. return true;
  49328. };
  49329. /**
  49330. * Get the element of the given key and remove it from the dictionary
  49331. * @param key
  49332. */
  49333. StringDictionary.prototype.getAndRemove = function (key) {
  49334. var val = this.get(key);
  49335. if (val !== undefined) {
  49336. delete this._data[key];
  49337. --this._count;
  49338. return val;
  49339. }
  49340. return null;
  49341. };
  49342. /**
  49343. * Remove a key/value from the dictionary.
  49344. * @param key the key to remove
  49345. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49346. */
  49347. StringDictionary.prototype.remove = function (key) {
  49348. if (this.contains(key)) {
  49349. delete this._data[key];
  49350. --this._count;
  49351. return true;
  49352. }
  49353. return false;
  49354. };
  49355. /**
  49356. * Clear the whole content of the dictionary
  49357. */
  49358. StringDictionary.prototype.clear = function () {
  49359. this._data = {};
  49360. this._count = 0;
  49361. };
  49362. Object.defineProperty(StringDictionary.prototype, "count", {
  49363. get: function () {
  49364. return this._count;
  49365. },
  49366. enumerable: true,
  49367. configurable: true
  49368. });
  49369. /**
  49370. * Execute a callback on each key/val of the dictionary.
  49371. * Note that you can remove any element in this dictionary in the callback implementation
  49372. * @param callback the callback to execute on a given key/value pair
  49373. */
  49374. StringDictionary.prototype.forEach = function (callback) {
  49375. for (var cur in this._data) {
  49376. var val = this._data[cur];
  49377. callback(cur, val);
  49378. }
  49379. };
  49380. /**
  49381. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49382. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49383. * Note that you can remove any element in this dictionary in the callback implementation
  49384. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49385. */
  49386. StringDictionary.prototype.first = function (callback) {
  49387. for (var cur in this._data) {
  49388. var val = this._data[cur];
  49389. var res = callback(cur, val);
  49390. if (res) {
  49391. return res;
  49392. }
  49393. }
  49394. return null;
  49395. };
  49396. return StringDictionary;
  49397. }());
  49398. BABYLON.StringDictionary = StringDictionary;
  49399. })(BABYLON || (BABYLON = {}));
  49400. //# sourceMappingURL=babylon.stringDictionary.js.map
  49401. var BABYLON;
  49402. (function (BABYLON) {
  49403. var Tags = (function () {
  49404. function Tags() {
  49405. }
  49406. Tags.EnableFor = function (obj) {
  49407. obj._tags = obj._tags || {};
  49408. obj.hasTags = function () {
  49409. return Tags.HasTags(obj);
  49410. };
  49411. obj.addTags = function (tagsString) {
  49412. return Tags.AddTagsTo(obj, tagsString);
  49413. };
  49414. obj.removeTags = function (tagsString) {
  49415. return Tags.RemoveTagsFrom(obj, tagsString);
  49416. };
  49417. obj.matchesTagsQuery = function (tagsQuery) {
  49418. return Tags.MatchesQuery(obj, tagsQuery);
  49419. };
  49420. };
  49421. Tags.DisableFor = function (obj) {
  49422. delete obj._tags;
  49423. delete obj.hasTags;
  49424. delete obj.addTags;
  49425. delete obj.removeTags;
  49426. delete obj.matchesTagsQuery;
  49427. };
  49428. Tags.HasTags = function (obj) {
  49429. if (!obj._tags) {
  49430. return false;
  49431. }
  49432. return !BABYLON.Tools.IsEmpty(obj._tags);
  49433. };
  49434. Tags.GetTags = function (obj, asString) {
  49435. if (asString === void 0) { asString = true; }
  49436. if (!obj._tags) {
  49437. return null;
  49438. }
  49439. if (asString) {
  49440. var tagsArray = [];
  49441. for (var tag in obj._tags) {
  49442. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  49443. tagsArray.push(tag);
  49444. }
  49445. }
  49446. return tagsArray.join(" ");
  49447. }
  49448. else {
  49449. return obj._tags;
  49450. }
  49451. };
  49452. // the tags 'true' and 'false' are reserved and cannot be used as tags
  49453. // a tag cannot start with '||', '&&', and '!'
  49454. // it cannot contain whitespaces
  49455. Tags.AddTagsTo = function (obj, tagsString) {
  49456. if (!tagsString) {
  49457. return;
  49458. }
  49459. if (typeof tagsString !== "string") {
  49460. return;
  49461. }
  49462. var tags = tagsString.split(" ");
  49463. tags.forEach(function (tag, index, array) {
  49464. Tags._AddTagTo(obj, tag);
  49465. });
  49466. };
  49467. Tags._AddTagTo = function (obj, tag) {
  49468. tag = tag.trim();
  49469. if (tag === "" || tag === "true" || tag === "false") {
  49470. return;
  49471. }
  49472. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  49473. return;
  49474. }
  49475. Tags.EnableFor(obj);
  49476. obj._tags[tag] = true;
  49477. };
  49478. Tags.RemoveTagsFrom = function (obj, tagsString) {
  49479. if (!Tags.HasTags(obj)) {
  49480. return;
  49481. }
  49482. var tags = tagsString.split(" ");
  49483. for (var t in tags) {
  49484. Tags._RemoveTagFrom(obj, tags[t]);
  49485. }
  49486. };
  49487. Tags._RemoveTagFrom = function (obj, tag) {
  49488. delete obj._tags[tag];
  49489. };
  49490. Tags.MatchesQuery = function (obj, tagsQuery) {
  49491. if (tagsQuery === undefined) {
  49492. return true;
  49493. }
  49494. if (tagsQuery === "") {
  49495. return Tags.HasTags(obj);
  49496. }
  49497. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  49498. };
  49499. return Tags;
  49500. }());
  49501. BABYLON.Tags = Tags;
  49502. })(BABYLON || (BABYLON = {}));
  49503. //# sourceMappingURL=babylon.tags.js.map
  49504. var BABYLON;
  49505. (function (BABYLON) {
  49506. var Internals;
  49507. (function (Internals) {
  49508. var AndOrNotEvaluator = (function () {
  49509. function AndOrNotEvaluator() {
  49510. }
  49511. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  49512. if (!query.match(/\([^\(\)]*\)/g)) {
  49513. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  49514. }
  49515. else {
  49516. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  49517. // remove parenthesis
  49518. r = r.slice(1, r.length - 1);
  49519. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  49520. });
  49521. }
  49522. if (query === "true") {
  49523. return true;
  49524. }
  49525. if (query === "false") {
  49526. return false;
  49527. }
  49528. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  49529. };
  49530. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  49531. evaluateCallback = evaluateCallback || (function (r) {
  49532. return r === "true" ? true : false;
  49533. });
  49534. var result;
  49535. var or = parenthesisContent.split("||");
  49536. for (var i in or) {
  49537. if (or.hasOwnProperty(i)) {
  49538. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  49539. var and = ori.split("&&");
  49540. if (and.length > 1) {
  49541. for (var j = 0; j < and.length; ++j) {
  49542. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  49543. if (andj !== "true" && andj !== "false") {
  49544. if (andj[0] === "!") {
  49545. result = !evaluateCallback(andj.substring(1));
  49546. }
  49547. else {
  49548. result = evaluateCallback(andj);
  49549. }
  49550. }
  49551. else {
  49552. result = andj === "true" ? true : false;
  49553. }
  49554. if (!result) {
  49555. ori = "false";
  49556. break;
  49557. }
  49558. }
  49559. }
  49560. if (result || ori === "true") {
  49561. result = true;
  49562. break;
  49563. }
  49564. // result equals false (or undefined)
  49565. if (ori !== "true" && ori !== "false") {
  49566. if (ori[0] === "!") {
  49567. result = !evaluateCallback(ori.substring(1));
  49568. }
  49569. else {
  49570. result = evaluateCallback(ori);
  49571. }
  49572. }
  49573. else {
  49574. result = ori === "true" ? true : false;
  49575. }
  49576. }
  49577. }
  49578. // the whole parenthesis scope is replaced by 'true' or 'false'
  49579. return result ? "true" : "false";
  49580. };
  49581. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  49582. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  49583. // remove whitespaces
  49584. r = r.replace(/[\s]/g, function () { return ""; });
  49585. return r.length % 2 ? "!" : "";
  49586. });
  49587. booleanString = booleanString.trim();
  49588. if (booleanString === "!true") {
  49589. booleanString = "false";
  49590. }
  49591. else if (booleanString === "!false") {
  49592. booleanString = "true";
  49593. }
  49594. return booleanString;
  49595. };
  49596. return AndOrNotEvaluator;
  49597. }());
  49598. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  49599. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49600. })(BABYLON || (BABYLON = {}));
  49601. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  49602. var BABYLON;
  49603. (function (BABYLON) {
  49604. var Database = (function () {
  49605. function Database(urlToScene, callbackManifestChecked) {
  49606. // Handling various flavors of prefixed version of IndexedDB
  49607. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  49608. this.callbackManifestChecked = callbackManifestChecked;
  49609. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  49610. this.db = null;
  49611. this.enableSceneOffline = false;
  49612. this.enableTexturesOffline = false;
  49613. this.manifestVersionFound = 0;
  49614. this.mustUpdateRessources = false;
  49615. this.hasReachedQuota = false;
  49616. if (!Database.IDBStorageEnabled) {
  49617. this.callbackManifestChecked(true);
  49618. }
  49619. else {
  49620. this.checkManifestFile();
  49621. }
  49622. }
  49623. Database.prototype.checkManifestFile = function () {
  49624. var _this = this;
  49625. function noManifestFile() {
  49626. that.enableSceneOffline = false;
  49627. that.enableTexturesOffline = false;
  49628. that.callbackManifestChecked(false);
  49629. }
  49630. var that = this;
  49631. var timeStampUsed = false;
  49632. var manifestURL = this.currentSceneUrl + ".manifest";
  49633. var xhr = new XMLHttpRequest();
  49634. if (navigator.onLine) {
  49635. // Adding a timestamp to by-pass browsers' cache
  49636. timeStampUsed = true;
  49637. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  49638. }
  49639. xhr.open("GET", manifestURL, true);
  49640. xhr.addEventListener("load", function () {
  49641. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49642. try {
  49643. var manifestFile = JSON.parse(xhr.response);
  49644. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  49645. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  49646. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  49647. _this.manifestVersionFound = manifestFile.version;
  49648. }
  49649. if (_this.callbackManifestChecked) {
  49650. _this.callbackManifestChecked(true);
  49651. }
  49652. }
  49653. catch (ex) {
  49654. noManifestFile();
  49655. }
  49656. }
  49657. else {
  49658. noManifestFile();
  49659. }
  49660. }, false);
  49661. xhr.addEventListener("error", function (event) {
  49662. if (timeStampUsed) {
  49663. timeStampUsed = false;
  49664. // Let's retry without the timeStamp
  49665. // It could fail when coupled with HTML5 Offline API
  49666. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49667. xhr.open("GET", retryManifestURL, true);
  49668. xhr.send();
  49669. }
  49670. else {
  49671. noManifestFile();
  49672. }
  49673. }, false);
  49674. try {
  49675. xhr.send();
  49676. }
  49677. catch (ex) {
  49678. BABYLON.Tools.Error("Error on XHR send request.");
  49679. that.callbackManifestChecked(false);
  49680. }
  49681. };
  49682. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49683. var _this = this;
  49684. function handleError() {
  49685. that.isSupported = false;
  49686. if (errorCallback)
  49687. errorCallback();
  49688. }
  49689. var that = this;
  49690. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49691. // Your browser doesn't support IndexedDB
  49692. this.isSupported = false;
  49693. if (errorCallback)
  49694. errorCallback();
  49695. }
  49696. else {
  49697. // If the DB hasn't been opened or created yet
  49698. if (!this.db) {
  49699. this.hasReachedQuota = false;
  49700. this.isSupported = true;
  49701. var request = this.idbFactory.open("babylonjs", 1);
  49702. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49703. request.onerror = function (event) {
  49704. handleError();
  49705. };
  49706. // executes when a version change transaction cannot complete due to other active transactions
  49707. request.onblocked = function (event) {
  49708. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49709. handleError();
  49710. };
  49711. // DB has been opened successfully
  49712. request.onsuccess = function (event) {
  49713. _this.db = request.result;
  49714. successCallback();
  49715. };
  49716. // Initialization of the DB. Creating Scenes & Textures stores
  49717. request.onupgradeneeded = function (event) {
  49718. _this.db = (event.target).result;
  49719. try {
  49720. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49721. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49722. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49723. }
  49724. catch (ex) {
  49725. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49726. handleError();
  49727. }
  49728. };
  49729. }
  49730. else {
  49731. if (successCallback)
  49732. successCallback();
  49733. }
  49734. }
  49735. };
  49736. Database.prototype.loadImageFromDB = function (url, image) {
  49737. var _this = this;
  49738. var completeURL = Database.ReturnFullUrlLocation(url);
  49739. var saveAndLoadImage = function () {
  49740. if (!_this.hasReachedQuota && _this.db !== null) {
  49741. // the texture is not yet in the DB, let's try to save it
  49742. _this._saveImageIntoDBAsync(completeURL, image);
  49743. }
  49744. else {
  49745. image.src = url;
  49746. }
  49747. };
  49748. if (!this.mustUpdateRessources) {
  49749. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49750. }
  49751. else {
  49752. saveAndLoadImage();
  49753. }
  49754. };
  49755. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49756. if (this.isSupported && this.db !== null) {
  49757. var texture;
  49758. var transaction = this.db.transaction(["textures"]);
  49759. transaction.onabort = function (event) {
  49760. image.src = url;
  49761. };
  49762. transaction.oncomplete = function (event) {
  49763. var blobTextureURL;
  49764. if (texture) {
  49765. var URL = window.URL || window.webkitURL;
  49766. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49767. image.onerror = function () {
  49768. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49769. image.src = url;
  49770. };
  49771. image.src = blobTextureURL;
  49772. }
  49773. else {
  49774. notInDBCallback();
  49775. }
  49776. };
  49777. var getRequest = transaction.objectStore("textures").get(url);
  49778. getRequest.onsuccess = function (event) {
  49779. texture = (event.target).result;
  49780. };
  49781. getRequest.onerror = function (event) {
  49782. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49783. image.src = url;
  49784. };
  49785. }
  49786. else {
  49787. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49788. image.src = url;
  49789. }
  49790. };
  49791. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49792. var _this = this;
  49793. if (this.isSupported) {
  49794. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49795. var generateBlobUrl = function () {
  49796. var blobTextureURL;
  49797. if (blob) {
  49798. var URL = window.URL || window.webkitURL;
  49799. try {
  49800. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  49801. }
  49802. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  49803. catch (ex) {
  49804. blobTextureURL = URL.createObjectURL(blob);
  49805. }
  49806. }
  49807. image.src = blobTextureURL;
  49808. };
  49809. if (Database.IsUASupportingBlobStorage) {
  49810. var xhr = new XMLHttpRequest(), blob;
  49811. xhr.open("GET", url, true);
  49812. xhr.responseType = "blob";
  49813. xhr.addEventListener("load", function () {
  49814. if (xhr.status === 200) {
  49815. // Blob as response (XHR2)
  49816. blob = xhr.response;
  49817. var transaction = _this.db.transaction(["textures"], "readwrite");
  49818. // the transaction could abort because of a QuotaExceededError error
  49819. transaction.onabort = function (event) {
  49820. try {
  49821. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49822. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49823. _this.hasReachedQuota = true;
  49824. }
  49825. }
  49826. catch (ex) { }
  49827. generateBlobUrl();
  49828. };
  49829. transaction.oncomplete = function (event) {
  49830. generateBlobUrl();
  49831. };
  49832. var newTexture = { textureUrl: url, data: blob };
  49833. try {
  49834. // Put the blob into the dabase
  49835. var addRequest = transaction.objectStore("textures").put(newTexture);
  49836. addRequest.onsuccess = function (event) {
  49837. };
  49838. addRequest.onerror = function (event) {
  49839. generateBlobUrl();
  49840. };
  49841. }
  49842. catch (ex) {
  49843. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  49844. if (ex.code === 25) {
  49845. Database.IsUASupportingBlobStorage = false;
  49846. }
  49847. image.src = url;
  49848. }
  49849. }
  49850. else {
  49851. image.src = url;
  49852. }
  49853. }, false);
  49854. xhr.addEventListener("error", function (event) {
  49855. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  49856. image.src = url;
  49857. }, false);
  49858. xhr.send();
  49859. }
  49860. else {
  49861. image.src = url;
  49862. }
  49863. }
  49864. else {
  49865. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49866. image.src = url;
  49867. }
  49868. };
  49869. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  49870. var _this = this;
  49871. var updateVersion = function (event) {
  49872. // the version is not yet in the DB or we need to update it
  49873. _this._saveVersionIntoDBAsync(url, versionLoaded);
  49874. };
  49875. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  49876. };
  49877. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  49878. var _this = this;
  49879. if (this.isSupported) {
  49880. var version;
  49881. try {
  49882. var transaction = this.db.transaction(["versions"]);
  49883. transaction.oncomplete = function (event) {
  49884. if (version) {
  49885. // If the version in the JSON file is > than the version in DB
  49886. if (_this.manifestVersionFound > version.data) {
  49887. _this.mustUpdateRessources = true;
  49888. updateInDBCallback();
  49889. }
  49890. else {
  49891. callback(version.data);
  49892. }
  49893. }
  49894. else {
  49895. _this.mustUpdateRessources = true;
  49896. updateInDBCallback();
  49897. }
  49898. };
  49899. transaction.onabort = function (event) {
  49900. callback(-1);
  49901. };
  49902. var getRequest = transaction.objectStore("versions").get(url);
  49903. getRequest.onsuccess = function (event) {
  49904. version = (event.target).result;
  49905. };
  49906. getRequest.onerror = function (event) {
  49907. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  49908. callback(-1);
  49909. };
  49910. }
  49911. catch (ex) {
  49912. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  49913. callback(-1);
  49914. }
  49915. }
  49916. else {
  49917. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49918. callback(-1);
  49919. }
  49920. };
  49921. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  49922. var _this = this;
  49923. if (this.isSupported && !this.hasReachedQuota) {
  49924. try {
  49925. // Open a transaction to the database
  49926. var transaction = this.db.transaction(["versions"], "readwrite");
  49927. // the transaction could abort because of a QuotaExceededError error
  49928. transaction.onabort = function (event) {
  49929. try {
  49930. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49931. _this.hasReachedQuota = true;
  49932. }
  49933. }
  49934. catch (ex) { }
  49935. callback(-1);
  49936. };
  49937. transaction.oncomplete = function (event) {
  49938. callback(_this.manifestVersionFound);
  49939. };
  49940. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  49941. // Put the scene into the database
  49942. var addRequest = transaction.objectStore("versions").put(newVersion);
  49943. addRequest.onsuccess = function (event) {
  49944. };
  49945. addRequest.onerror = function (event) {
  49946. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  49947. };
  49948. }
  49949. catch (ex) {
  49950. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  49951. callback(-1);
  49952. }
  49953. }
  49954. else {
  49955. callback(-1);
  49956. }
  49957. };
  49958. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  49959. var _this = this;
  49960. var completeUrl = Database.ReturnFullUrlLocation(url);
  49961. var saveAndLoadFile = function (event) {
  49962. // the scene is not yet in the DB, let's try to save it
  49963. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  49964. };
  49965. this._checkVersionFromDB(completeUrl, function (version) {
  49966. if (version !== -1) {
  49967. if (!_this.mustUpdateRessources) {
  49968. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  49969. }
  49970. else {
  49971. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  49972. }
  49973. }
  49974. else {
  49975. errorCallback();
  49976. }
  49977. });
  49978. };
  49979. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  49980. if (this.isSupported) {
  49981. var targetStore;
  49982. if (url.indexOf(".babylon") !== -1) {
  49983. targetStore = "scenes";
  49984. }
  49985. else {
  49986. targetStore = "textures";
  49987. }
  49988. var file;
  49989. var transaction = this.db.transaction([targetStore]);
  49990. transaction.oncomplete = function (event) {
  49991. if (file) {
  49992. callback(file.data);
  49993. }
  49994. else {
  49995. notInDBCallback();
  49996. }
  49997. };
  49998. transaction.onabort = function (event) {
  49999. notInDBCallback();
  50000. };
  50001. var getRequest = transaction.objectStore(targetStore).get(url);
  50002. getRequest.onsuccess = function (event) {
  50003. file = (event.target).result;
  50004. };
  50005. getRequest.onerror = function (event) {
  50006. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  50007. notInDBCallback();
  50008. };
  50009. }
  50010. else {
  50011. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50012. callback();
  50013. }
  50014. };
  50015. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  50016. var _this = this;
  50017. if (this.isSupported) {
  50018. var targetStore;
  50019. if (url.indexOf(".babylon") !== -1) {
  50020. targetStore = "scenes";
  50021. }
  50022. else {
  50023. targetStore = "textures";
  50024. }
  50025. // Create XHR
  50026. var xhr = new XMLHttpRequest(), fileData;
  50027. xhr.open("GET", url, true);
  50028. if (useArrayBuffer) {
  50029. xhr.responseType = "arraybuffer";
  50030. }
  50031. xhr.onprogress = progressCallback;
  50032. xhr.addEventListener("load", function () {
  50033. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  50034. // Blob as response (XHR2)
  50035. //fileData = xhr.responseText;
  50036. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  50037. if (!_this.hasReachedQuota) {
  50038. // Open a transaction to the database
  50039. var transaction = _this.db.transaction([targetStore], "readwrite");
  50040. // the transaction could abort because of a QuotaExceededError error
  50041. transaction.onabort = function (event) {
  50042. try {
  50043. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50044. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50045. _this.hasReachedQuota = true;
  50046. }
  50047. }
  50048. catch (ex) { }
  50049. callback(fileData);
  50050. };
  50051. transaction.oncomplete = function (event) {
  50052. callback(fileData);
  50053. };
  50054. var newFile;
  50055. if (targetStore === "scenes") {
  50056. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  50057. }
  50058. else {
  50059. newFile = { textureUrl: url, data: fileData };
  50060. }
  50061. try {
  50062. // Put the scene into the database
  50063. var addRequest = transaction.objectStore(targetStore).put(newFile);
  50064. addRequest.onsuccess = function (event) {
  50065. };
  50066. addRequest.onerror = function (event) {
  50067. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  50068. };
  50069. }
  50070. catch (ex) {
  50071. callback(fileData);
  50072. }
  50073. }
  50074. else {
  50075. callback(fileData);
  50076. }
  50077. }
  50078. else {
  50079. callback();
  50080. }
  50081. }, false);
  50082. xhr.addEventListener("error", function (event) {
  50083. BABYLON.Tools.Error("error on XHR request.");
  50084. callback();
  50085. }, false);
  50086. xhr.send();
  50087. }
  50088. else {
  50089. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50090. callback();
  50091. }
  50092. };
  50093. Database.IsUASupportingBlobStorage = true;
  50094. Database.IDBStorageEnabled = true;
  50095. Database.parseURL = function (url) {
  50096. var a = document.createElement('a');
  50097. a.href = url;
  50098. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  50099. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  50100. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  50101. return absLocation;
  50102. };
  50103. Database.ReturnFullUrlLocation = function (url) {
  50104. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  50105. return (Database.parseURL(window.location.href) + url);
  50106. }
  50107. else {
  50108. return url;
  50109. }
  50110. };
  50111. return Database;
  50112. }());
  50113. BABYLON.Database = Database;
  50114. })(BABYLON || (BABYLON = {}));
  50115. //# sourceMappingURL=babylon.database.js.map
  50116. var BABYLON;
  50117. (function (BABYLON) {
  50118. var FresnelParameters = (function () {
  50119. function FresnelParameters() {
  50120. this._isEnabled = true;
  50121. this.leftColor = BABYLON.Color3.White();
  50122. this.rightColor = BABYLON.Color3.Black();
  50123. this.bias = 0;
  50124. this.power = 1;
  50125. }
  50126. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  50127. get: function () {
  50128. return this._isEnabled;
  50129. },
  50130. set: function (value) {
  50131. if (this._isEnabled === value) {
  50132. return;
  50133. }
  50134. this._isEnabled = value;
  50135. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. FresnelParameters.prototype.clone = function () {
  50141. var newFresnelParameters = new FresnelParameters();
  50142. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50143. return newFresnelParameters;
  50144. };
  50145. FresnelParameters.prototype.serialize = function () {
  50146. var serializationObject = {};
  50147. serializationObject.isEnabled = this.isEnabled;
  50148. serializationObject.leftColor = this.leftColor;
  50149. serializationObject.rightColor = this.rightColor;
  50150. serializationObject.bias = this.bias;
  50151. serializationObject.power = this.power;
  50152. return serializationObject;
  50153. };
  50154. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50155. var fresnelParameters = new FresnelParameters();
  50156. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50157. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50158. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50159. fresnelParameters.bias = parsedFresnelParameters.bias;
  50160. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50161. return fresnelParameters;
  50162. };
  50163. return FresnelParameters;
  50164. }());
  50165. BABYLON.FresnelParameters = FresnelParameters;
  50166. })(BABYLON || (BABYLON = {}));
  50167. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50168. var BABYLON;
  50169. (function (BABYLON) {
  50170. var MultiMaterial = (function (_super) {
  50171. __extends(MultiMaterial, _super);
  50172. function MultiMaterial(name, scene) {
  50173. var _this = _super.call(this, name, scene, true) || this;
  50174. scene.multiMaterials.push(_this);
  50175. _this.subMaterials = new Array();
  50176. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50177. return _this;
  50178. }
  50179. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50180. get: function () {
  50181. return this._subMaterials;
  50182. },
  50183. set: function (value) {
  50184. this._subMaterials = value;
  50185. this._hookArray(value);
  50186. },
  50187. enumerable: true,
  50188. configurable: true
  50189. });
  50190. MultiMaterial.prototype._hookArray = function (array) {
  50191. var _this = this;
  50192. var oldPush = array.push;
  50193. array.push = function () {
  50194. var items = [];
  50195. for (var _i = 0; _i < arguments.length; _i++) {
  50196. items[_i] = arguments[_i];
  50197. }
  50198. var result = oldPush.apply(array, items);
  50199. _this._markAllSubMeshesAsTexturesDirty();
  50200. return result;
  50201. };
  50202. var oldSplice = array.splice;
  50203. array.splice = function (index, deleteCount) {
  50204. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50205. _this._markAllSubMeshesAsTexturesDirty();
  50206. return deleted;
  50207. };
  50208. };
  50209. // Properties
  50210. MultiMaterial.prototype.getSubMaterial = function (index) {
  50211. if (index < 0 || index >= this.subMaterials.length) {
  50212. return this.getScene().defaultMaterial;
  50213. }
  50214. return this.subMaterials[index];
  50215. };
  50216. MultiMaterial.prototype.getActiveTextures = function () {
  50217. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50218. var _a;
  50219. };
  50220. // Methods
  50221. MultiMaterial.prototype.getClassName = function () {
  50222. return "MultiMaterial";
  50223. };
  50224. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50225. for (var index = 0; index < this.subMaterials.length; index++) {
  50226. var subMaterial = this.subMaterials[index];
  50227. if (subMaterial) {
  50228. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50229. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50230. return false;
  50231. }
  50232. continue;
  50233. }
  50234. if (!this.subMaterials[index].isReady(mesh)) {
  50235. return false;
  50236. }
  50237. }
  50238. }
  50239. return true;
  50240. };
  50241. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50242. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50243. for (var index = 0; index < this.subMaterials.length; index++) {
  50244. var subMaterial = null;
  50245. if (cloneChildren) {
  50246. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50247. }
  50248. else {
  50249. subMaterial = this.subMaterials[index];
  50250. }
  50251. newMultiMaterial.subMaterials.push(subMaterial);
  50252. }
  50253. return newMultiMaterial;
  50254. };
  50255. MultiMaterial.prototype.serialize = function () {
  50256. var serializationObject = {};
  50257. serializationObject.name = this.name;
  50258. serializationObject.id = this.id;
  50259. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50260. serializationObject.materials = [];
  50261. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50262. var subMat = this.subMaterials[matIndex];
  50263. if (subMat) {
  50264. serializationObject.materials.push(subMat.id);
  50265. }
  50266. else {
  50267. serializationObject.materials.push(null);
  50268. }
  50269. }
  50270. return serializationObject;
  50271. };
  50272. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50273. var scene = this.getScene();
  50274. if (!scene) {
  50275. return;
  50276. }
  50277. var index = scene.multiMaterials.indexOf(this);
  50278. if (index >= 0) {
  50279. scene.multiMaterials.splice(index, 1);
  50280. }
  50281. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50282. };
  50283. return MultiMaterial;
  50284. }(BABYLON.Material));
  50285. BABYLON.MultiMaterial = MultiMaterial;
  50286. })(BABYLON || (BABYLON = {}));
  50287. //# sourceMappingURL=babylon.multiMaterial.js.map
  50288. var BABYLON;
  50289. (function (BABYLON) {
  50290. var FreeCameraTouchInput = (function () {
  50291. function FreeCameraTouchInput() {
  50292. this._offsetX = null;
  50293. this._offsetY = null;
  50294. this._pointerCount = 0;
  50295. this._pointerPressed = [];
  50296. this.touchAngularSensibility = 200000.0;
  50297. this.touchMoveSensibility = 250.0;
  50298. }
  50299. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50300. var _this = this;
  50301. var previousPosition;
  50302. if (this._pointerInput === undefined) {
  50303. this._onLostFocus = function (evt) {
  50304. _this._offsetX = null;
  50305. _this._offsetY = null;
  50306. };
  50307. this._pointerInput = function (p, s) {
  50308. var evt = p.event;
  50309. if (evt.pointerType === "mouse") {
  50310. return;
  50311. }
  50312. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50313. if (!noPreventDefault) {
  50314. evt.preventDefault();
  50315. }
  50316. _this._pointerPressed.push(evt.pointerId);
  50317. if (_this._pointerPressed.length !== 1) {
  50318. return;
  50319. }
  50320. previousPosition = {
  50321. x: evt.clientX,
  50322. y: evt.clientY
  50323. };
  50324. }
  50325. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50326. if (!noPreventDefault) {
  50327. evt.preventDefault();
  50328. }
  50329. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50330. if (index === -1) {
  50331. return;
  50332. }
  50333. _this._pointerPressed.splice(index, 1);
  50334. if (index != 0) {
  50335. return;
  50336. }
  50337. previousPosition = null;
  50338. _this._offsetX = null;
  50339. _this._offsetY = null;
  50340. }
  50341. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50342. if (!noPreventDefault) {
  50343. evt.preventDefault();
  50344. }
  50345. if (!previousPosition) {
  50346. return;
  50347. }
  50348. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50349. if (index != 0) {
  50350. return;
  50351. }
  50352. _this._offsetX = evt.clientX - previousPosition.x;
  50353. _this._offsetY = -(evt.clientY - previousPosition.y);
  50354. }
  50355. };
  50356. }
  50357. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50358. element.addEventListener("blur", this._onLostFocus);
  50359. };
  50360. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50361. if (this._pointerInput && element) {
  50362. this.camera.getScene().onPointerObservable.remove(this._observer);
  50363. this._observer = null;
  50364. element.removeEventListener("blur", this._onLostFocus);
  50365. this._onLostFocus = null;
  50366. this._pointerPressed = [];
  50367. this._offsetX = null;
  50368. this._offsetY = null;
  50369. this._pointerCount = 0;
  50370. }
  50371. };
  50372. FreeCameraTouchInput.prototype.checkInputs = function () {
  50373. if (this._offsetX) {
  50374. var camera = this.camera;
  50375. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50376. if (this._pointerPressed.length > 1) {
  50377. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50378. }
  50379. else {
  50380. var speed = camera._computeLocalCameraSpeed();
  50381. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50382. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50383. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50384. }
  50385. }
  50386. };
  50387. FreeCameraTouchInput.prototype.getClassName = function () {
  50388. return "FreeCameraTouchInput";
  50389. };
  50390. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50391. return "touch";
  50392. };
  50393. __decorate([
  50394. BABYLON.serialize()
  50395. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50396. __decorate([
  50397. BABYLON.serialize()
  50398. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50399. return FreeCameraTouchInput;
  50400. }());
  50401. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50402. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50403. })(BABYLON || (BABYLON = {}));
  50404. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50405. /// <reference path="babylon.freeCamera.ts" />
  50406. var BABYLON;
  50407. (function (BABYLON) {
  50408. // We're mainly based on the logic defined into the FreeCamera code
  50409. var TouchCamera = (function (_super) {
  50410. __extends(TouchCamera, _super);
  50411. //-- end properties for backward compatibility for inputs
  50412. function TouchCamera(name, position, scene) {
  50413. var _this = _super.call(this, name, position, scene) || this;
  50414. _this.inputs.addTouch();
  50415. _this._setupInputs();
  50416. return _this;
  50417. }
  50418. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50419. //-- Begin properties for backward compatibility for inputs
  50420. get: function () {
  50421. var touch = this.inputs.attached["touch"];
  50422. if (touch)
  50423. return touch.touchAngularSensibility;
  50424. },
  50425. set: function (value) {
  50426. var touch = this.inputs.attached["touch"];
  50427. if (touch)
  50428. touch.touchAngularSensibility = value;
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  50434. get: function () {
  50435. var touch = this.inputs.attached["touch"];
  50436. if (touch)
  50437. return touch.touchMoveSensibility;
  50438. },
  50439. set: function (value) {
  50440. var touch = this.inputs.attached["touch"];
  50441. if (touch)
  50442. touch.touchMoveSensibility = value;
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. TouchCamera.prototype.getClassName = function () {
  50448. return "TouchCamera";
  50449. };
  50450. TouchCamera.prototype._setupInputs = function () {
  50451. var mouse = this.inputs.attached["mouse"];
  50452. if (mouse) {
  50453. mouse.touchEnabled = false;
  50454. }
  50455. };
  50456. return TouchCamera;
  50457. }(BABYLON.FreeCamera));
  50458. BABYLON.TouchCamera = TouchCamera;
  50459. })(BABYLON || (BABYLON = {}));
  50460. //# sourceMappingURL=babylon.touchCamera.js.map
  50461. var BABYLON;
  50462. (function (BABYLON) {
  50463. var ProceduralTexture = (function (_super) {
  50464. __extends(ProceduralTexture, _super);
  50465. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  50466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50467. if (isCube === void 0) { isCube = false; }
  50468. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50469. _this.isCube = isCube;
  50470. _this.isEnabled = true;
  50471. _this._currentRefreshId = -1;
  50472. _this._refreshRate = 1;
  50473. _this._vertexBuffers = {};
  50474. _this._uniforms = new Array();
  50475. _this._samplers = new Array();
  50476. _this._textures = new Array();
  50477. _this._floats = new Array();
  50478. _this._floatsArrays = {};
  50479. _this._colors3 = new Array();
  50480. _this._colors4 = new Array();
  50481. _this._vectors2 = new Array();
  50482. _this._vectors3 = new Array();
  50483. _this._matrices = new Array();
  50484. _this._fallbackTextureUsed = false;
  50485. scene._proceduralTextures.push(_this);
  50486. _this.name = name;
  50487. _this.isRenderTarget = true;
  50488. _this._size = size;
  50489. _this._generateMipMaps = generateMipMaps;
  50490. _this.setFragment(fragment);
  50491. _this._fallbackTexture = fallbackTexture;
  50492. var engine = scene.getEngine();
  50493. if (isCube) {
  50494. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  50495. _this.setFloat("face", 0);
  50496. }
  50497. else {
  50498. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  50499. }
  50500. // VBO
  50501. var vertices = [];
  50502. vertices.push(1, 1);
  50503. vertices.push(-1, 1);
  50504. vertices.push(-1, -1);
  50505. vertices.push(1, -1);
  50506. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50507. _this._createIndexBuffer();
  50508. return _this;
  50509. }
  50510. ProceduralTexture.prototype._createIndexBuffer = function () {
  50511. var engine = this.getScene().getEngine();
  50512. // Indices
  50513. var indices = [];
  50514. indices.push(0);
  50515. indices.push(1);
  50516. indices.push(2);
  50517. indices.push(0);
  50518. indices.push(2);
  50519. indices.push(3);
  50520. this._indexBuffer = engine.createIndexBuffer(indices);
  50521. };
  50522. ProceduralTexture.prototype._rebuild = function () {
  50523. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  50524. this._createIndexBuffer();
  50525. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50526. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50527. }
  50528. };
  50529. ProceduralTexture.prototype.reset = function () {
  50530. if (this._effect === undefined) {
  50531. return;
  50532. }
  50533. var engine = this.getScene().getEngine();
  50534. engine._releaseEffect(this._effect);
  50535. };
  50536. ProceduralTexture.prototype.isReady = function () {
  50537. var _this = this;
  50538. var engine = this.getScene().getEngine();
  50539. var shaders;
  50540. if (!this._fragment) {
  50541. return false;
  50542. }
  50543. if (this._fallbackTextureUsed) {
  50544. return true;
  50545. }
  50546. if (this._fragment.fragmentElement !== undefined) {
  50547. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  50548. }
  50549. else {
  50550. shaders = { vertex: "procedural", fragment: this._fragment };
  50551. }
  50552. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  50553. _this.releaseInternalTexture();
  50554. if (_this._fallbackTexture) {
  50555. _this._texture = _this._fallbackTexture._texture;
  50556. _this._texture.incrementReferences();
  50557. }
  50558. _this._fallbackTextureUsed = true;
  50559. });
  50560. return this._effect.isReady();
  50561. };
  50562. ProceduralTexture.prototype.resetRefreshCounter = function () {
  50563. this._currentRefreshId = -1;
  50564. };
  50565. ProceduralTexture.prototype.setFragment = function (fragment) {
  50566. this._fragment = fragment;
  50567. };
  50568. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  50569. get: function () {
  50570. return this._refreshRate;
  50571. },
  50572. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50573. set: function (value) {
  50574. this._refreshRate = value;
  50575. this.resetRefreshCounter();
  50576. },
  50577. enumerable: true,
  50578. configurable: true
  50579. });
  50580. ProceduralTexture.prototype._shouldRender = function () {
  50581. if (!this.isEnabled || !this.isReady() || !this._texture) {
  50582. return false;
  50583. }
  50584. if (this._fallbackTextureUsed) {
  50585. return false;
  50586. }
  50587. if (this._currentRefreshId === -1) {
  50588. this._currentRefreshId = 1;
  50589. return true;
  50590. }
  50591. if (this.refreshRate === this._currentRefreshId) {
  50592. this._currentRefreshId = 1;
  50593. return true;
  50594. }
  50595. this._currentRefreshId++;
  50596. return false;
  50597. };
  50598. ProceduralTexture.prototype.getRenderSize = function () {
  50599. return this._size;
  50600. };
  50601. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  50602. if (this._fallbackTextureUsed) {
  50603. return;
  50604. }
  50605. this.releaseInternalTexture();
  50606. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  50607. };
  50608. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  50609. if (this._uniforms.indexOf(uniformName) === -1) {
  50610. this._uniforms.push(uniformName);
  50611. }
  50612. };
  50613. ProceduralTexture.prototype.setTexture = function (name, texture) {
  50614. if (this._samplers.indexOf(name) === -1) {
  50615. this._samplers.push(name);
  50616. }
  50617. this._textures[name] = texture;
  50618. return this;
  50619. };
  50620. ProceduralTexture.prototype.setFloat = function (name, value) {
  50621. this._checkUniform(name);
  50622. this._floats[name] = value;
  50623. return this;
  50624. };
  50625. ProceduralTexture.prototype.setFloats = function (name, value) {
  50626. this._checkUniform(name);
  50627. this._floatsArrays[name] = value;
  50628. return this;
  50629. };
  50630. ProceduralTexture.prototype.setColor3 = function (name, value) {
  50631. this._checkUniform(name);
  50632. this._colors3[name] = value;
  50633. return this;
  50634. };
  50635. ProceduralTexture.prototype.setColor4 = function (name, value) {
  50636. this._checkUniform(name);
  50637. this._colors4[name] = value;
  50638. return this;
  50639. };
  50640. ProceduralTexture.prototype.setVector2 = function (name, value) {
  50641. this._checkUniform(name);
  50642. this._vectors2[name] = value;
  50643. return this;
  50644. };
  50645. ProceduralTexture.prototype.setVector3 = function (name, value) {
  50646. this._checkUniform(name);
  50647. this._vectors3[name] = value;
  50648. return this;
  50649. };
  50650. ProceduralTexture.prototype.setMatrix = function (name, value) {
  50651. this._checkUniform(name);
  50652. this._matrices[name] = value;
  50653. return this;
  50654. };
  50655. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50656. var scene = this.getScene();
  50657. var engine = scene.getEngine();
  50658. // Render
  50659. engine.enableEffect(this._effect);
  50660. engine.setState(false);
  50661. // Texture
  50662. for (var name in this._textures) {
  50663. this._effect.setTexture(name, this._textures[name]);
  50664. }
  50665. // Float
  50666. for (name in this._floats) {
  50667. this._effect.setFloat(name, this._floats[name]);
  50668. }
  50669. // Floats
  50670. for (name in this._floatsArrays) {
  50671. this._effect.setArray(name, this._floatsArrays[name]);
  50672. }
  50673. // Color3
  50674. for (name in this._colors3) {
  50675. this._effect.setColor3(name, this._colors3[name]);
  50676. }
  50677. // Color4
  50678. for (name in this._colors4) {
  50679. var color = this._colors4[name];
  50680. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50681. }
  50682. // Vector2
  50683. for (name in this._vectors2) {
  50684. this._effect.setVector2(name, this._vectors2[name]);
  50685. }
  50686. // Vector3
  50687. for (name in this._vectors3) {
  50688. this._effect.setVector3(name, this._vectors3[name]);
  50689. }
  50690. // Matrix
  50691. for (name in this._matrices) {
  50692. this._effect.setMatrix(name, this._matrices[name]);
  50693. }
  50694. if (this.isCube) {
  50695. for (var face = 0; face < 6; face++) {
  50696. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50697. // VBOs
  50698. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50699. this._effect.setFloat("face", face);
  50700. // Clear
  50701. engine.clear(scene.clearColor, true, true, true);
  50702. // Draw order
  50703. engine.draw(true, 0, 6);
  50704. // Mipmaps
  50705. if (face === 5) {
  50706. engine.generateMipMapsForCubemap(this._texture);
  50707. }
  50708. }
  50709. }
  50710. else {
  50711. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50712. // VBOs
  50713. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50714. // Clear
  50715. engine.clear(scene.clearColor, true, true, true);
  50716. // Draw order
  50717. engine.draw(true, 0, 6);
  50718. }
  50719. // Unbind
  50720. engine.unBindFramebuffer(this._texture, this.isCube);
  50721. if (this.onGenerated) {
  50722. this.onGenerated();
  50723. }
  50724. };
  50725. ProceduralTexture.prototype.clone = function () {
  50726. var textureSize = this.getSize();
  50727. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50728. // Base texture
  50729. newTexture.hasAlpha = this.hasAlpha;
  50730. newTexture.level = this.level;
  50731. // RenderTarget Texture
  50732. newTexture.coordinatesMode = this.coordinatesMode;
  50733. return newTexture;
  50734. };
  50735. ProceduralTexture.prototype.dispose = function () {
  50736. var index = this.getScene()._proceduralTextures.indexOf(this);
  50737. if (index >= 0) {
  50738. this.getScene()._proceduralTextures.splice(index, 1);
  50739. }
  50740. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50741. if (vertexBuffer) {
  50742. vertexBuffer.dispose();
  50743. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50744. }
  50745. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50746. this._indexBuffer = null;
  50747. }
  50748. _super.prototype.dispose.call(this);
  50749. };
  50750. return ProceduralTexture;
  50751. }(BABYLON.Texture));
  50752. BABYLON.ProceduralTexture = ProceduralTexture;
  50753. })(BABYLON || (BABYLON = {}));
  50754. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50755. /// <reference path="babylon.proceduralTexture.ts" />
  50756. var BABYLON;
  50757. (function (BABYLON) {
  50758. var CustomProceduralTexture = (function (_super) {
  50759. __extends(CustomProceduralTexture, _super);
  50760. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50761. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50762. _this._animate = true;
  50763. _this._time = 0;
  50764. _this._texturePath = texturePath;
  50765. //Try to load json
  50766. _this.loadJson(texturePath);
  50767. _this.refreshRate = 1;
  50768. return _this;
  50769. }
  50770. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50771. var _this = this;
  50772. var that = this;
  50773. function noConfigFile() {
  50774. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50775. try {
  50776. that.setFragment(that._texturePath);
  50777. }
  50778. catch (ex) {
  50779. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50780. }
  50781. }
  50782. var configFileUrl = jsonUrl + "/config.json";
  50783. var xhr = new XMLHttpRequest();
  50784. xhr.open("GET", configFileUrl, true);
  50785. xhr.addEventListener("load", function () {
  50786. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50787. try {
  50788. _this._config = JSON.parse(xhr.response);
  50789. _this.updateShaderUniforms();
  50790. _this.updateTextures();
  50791. _this.setFragment(_this._texturePath + "/custom");
  50792. _this._animate = _this._config.animate;
  50793. _this.refreshRate = _this._config.refreshrate;
  50794. }
  50795. catch (ex) {
  50796. noConfigFile();
  50797. }
  50798. }
  50799. else {
  50800. noConfigFile();
  50801. }
  50802. }, false);
  50803. xhr.addEventListener("error", function () {
  50804. noConfigFile();
  50805. }, false);
  50806. try {
  50807. xhr.send();
  50808. }
  50809. catch (ex) {
  50810. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  50811. }
  50812. };
  50813. CustomProceduralTexture.prototype.isReady = function () {
  50814. if (!_super.prototype.isReady.call(this)) {
  50815. return false;
  50816. }
  50817. for (var name in this._textures) {
  50818. var texture = this._textures[name];
  50819. if (!texture.isReady()) {
  50820. return false;
  50821. }
  50822. }
  50823. return true;
  50824. };
  50825. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50826. if (this._animate) {
  50827. this._time += this.getScene().getAnimationRatio() * 0.03;
  50828. this.updateShaderUniforms();
  50829. }
  50830. _super.prototype.render.call(this, useCameraPostProcess);
  50831. };
  50832. CustomProceduralTexture.prototype.updateTextures = function () {
  50833. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  50834. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  50835. }
  50836. };
  50837. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  50838. if (this._config) {
  50839. for (var j = 0; j < this._config.uniforms.length; j++) {
  50840. var uniform = this._config.uniforms[j];
  50841. switch (uniform.type) {
  50842. case "float":
  50843. this.setFloat(uniform.name, uniform.value);
  50844. break;
  50845. case "color3":
  50846. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  50847. break;
  50848. case "color4":
  50849. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  50850. break;
  50851. case "vector2":
  50852. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  50853. break;
  50854. case "vector3":
  50855. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  50856. break;
  50857. }
  50858. }
  50859. }
  50860. this.setFloat("time", this._time);
  50861. };
  50862. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  50863. get: function () {
  50864. return this._animate;
  50865. },
  50866. set: function (value) {
  50867. this._animate = value;
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. return CustomProceduralTexture;
  50873. }(BABYLON.ProceduralTexture));
  50874. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  50875. })(BABYLON || (BABYLON = {}));
  50876. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  50877. var BABYLON;
  50878. (function (BABYLON) {
  50879. var FreeCameraGamepadInput = (function () {
  50880. function FreeCameraGamepadInput() {
  50881. this.gamepadAngularSensibility = 200;
  50882. this.gamepadMoveSensibility = 40;
  50883. // private members
  50884. this._cameraTransform = BABYLON.Matrix.Identity();
  50885. this._deltaTransform = BABYLON.Vector3.Zero();
  50886. this._vector3 = BABYLON.Vector3.Zero();
  50887. this._vector2 = BABYLON.Vector2.Zero();
  50888. }
  50889. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50890. var _this = this;
  50891. var manager = this.camera.getScene().gamepadManager;
  50892. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50893. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50894. // prioritize XBOX gamepads.
  50895. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50896. _this.gamepad = gamepad;
  50897. }
  50898. }
  50899. });
  50900. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50901. if (_this.gamepad === gamepad) {
  50902. _this.gamepad = null;
  50903. }
  50904. });
  50905. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50906. };
  50907. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  50908. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50909. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50910. this.gamepad = null;
  50911. };
  50912. FreeCameraGamepadInput.prototype.checkInputs = function () {
  50913. if (this.gamepad && this.gamepad.leftStick) {
  50914. var camera = this.camera;
  50915. var LSValues = this.gamepad.leftStick;
  50916. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  50917. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50918. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  50919. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  50920. var RSValues = this.gamepad.rightStick;
  50921. if (RSValues) {
  50922. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  50923. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  50924. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  50925. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  50926. }
  50927. else {
  50928. RSValues = { x: 0, y: 0 };
  50929. }
  50930. if (!camera.rotationQuaternion) {
  50931. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  50932. }
  50933. else {
  50934. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  50935. }
  50936. var speed = camera._computeLocalCameraSpeed() * 50.0;
  50937. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  50938. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  50939. camera.cameraDirection.addInPlace(this._deltaTransform);
  50940. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  50941. camera.cameraRotation.addInPlace(this._vector2);
  50942. }
  50943. };
  50944. FreeCameraGamepadInput.prototype.getClassName = function () {
  50945. return "FreeCameraGamepadInput";
  50946. };
  50947. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  50948. return "gamepad";
  50949. };
  50950. __decorate([
  50951. BABYLON.serialize()
  50952. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  50953. __decorate([
  50954. BABYLON.serialize()
  50955. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50956. return FreeCameraGamepadInput;
  50957. }());
  50958. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  50959. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  50960. })(BABYLON || (BABYLON = {}));
  50961. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  50962. var BABYLON;
  50963. (function (BABYLON) {
  50964. var ArcRotateCameraGamepadInput = (function () {
  50965. function ArcRotateCameraGamepadInput() {
  50966. this.gamepadRotationSensibility = 80;
  50967. this.gamepadMoveSensibility = 40;
  50968. }
  50969. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50970. var _this = this;
  50971. var manager = this.camera.getScene().gamepadManager;
  50972. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50973. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50974. // prioritize XBOX gamepads.
  50975. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50976. _this.gamepad = gamepad;
  50977. }
  50978. }
  50979. });
  50980. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50981. if (_this.gamepad === gamepad) {
  50982. _this.gamepad = null;
  50983. }
  50984. });
  50985. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50986. };
  50987. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  50988. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50989. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50990. this.gamepad = null;
  50991. };
  50992. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  50993. if (this.gamepad) {
  50994. var camera = this.camera;
  50995. var RSValues = this.gamepad.rightStick;
  50996. if (RSValues) {
  50997. if (RSValues.x != 0) {
  50998. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  50999. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  51000. camera.inertialAlphaOffset += normalizedRX;
  51001. }
  51002. }
  51003. if (RSValues.y != 0) {
  51004. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  51005. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  51006. camera.inertialBetaOffset += normalizedRY;
  51007. }
  51008. }
  51009. }
  51010. var LSValues = this.gamepad.leftStick;
  51011. if (LSValues && LSValues.y != 0) {
  51012. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51013. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  51014. this.camera.inertialRadiusOffset -= normalizedLY;
  51015. }
  51016. }
  51017. }
  51018. };
  51019. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  51020. return "ArcRotateCameraGamepadInput";
  51021. };
  51022. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  51023. return "gamepad";
  51024. };
  51025. __decorate([
  51026. BABYLON.serialize()
  51027. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  51028. __decorate([
  51029. BABYLON.serialize()
  51030. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51031. return ArcRotateCameraGamepadInput;
  51032. }());
  51033. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  51034. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  51035. })(BABYLON || (BABYLON = {}));
  51036. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  51037. var BABYLON;
  51038. (function (BABYLON) {
  51039. var GamepadManager = (function () {
  51040. function GamepadManager() {
  51041. var _this = this;
  51042. this._babylonGamepads = [];
  51043. this._oneGamepadConnected = false;
  51044. this._isMonitoring = false;
  51045. this._gamepadEventSupported = 'GamepadEvent' in window;
  51046. this._gamepadSupport = (navigator.getGamepads ||
  51047. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51048. this.onGamepadConnectedObservable = new BABYLON.Observable();
  51049. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  51050. this._onGamepadConnectedEvent = function (evt) {
  51051. var gamepad = evt.gamepad;
  51052. if (gamepad.index in _this._babylonGamepads) {
  51053. if (_this._babylonGamepads[gamepad.index].isConnected) {
  51054. return;
  51055. }
  51056. }
  51057. var newGamepad;
  51058. if (_this._babylonGamepads[gamepad.index]) {
  51059. newGamepad = _this._babylonGamepads[gamepad.index];
  51060. newGamepad.browserGamepad = gamepad;
  51061. newGamepad._isConnected = true;
  51062. }
  51063. else {
  51064. newGamepad = _this._addNewGamepad(gamepad);
  51065. }
  51066. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51067. _this._startMonitoringGamepads();
  51068. };
  51069. this._onGamepadDisconnectedEvent = function (evt) {
  51070. var gamepad = evt.gamepad;
  51071. // Remove the gamepad from the list of gamepads to monitor.
  51072. for (var i in _this._babylonGamepads) {
  51073. if (_this._babylonGamepads[i].index === gamepad.index) {
  51074. var disconnectedGamepad = _this._babylonGamepads[i];
  51075. disconnectedGamepad._isConnected = false;
  51076. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  51077. break;
  51078. }
  51079. }
  51080. };
  51081. if (this._gamepadSupport) {
  51082. //first add already-connected gamepads
  51083. this._updateGamepadObjects();
  51084. if (this._babylonGamepads.length) {
  51085. this._startMonitoringGamepads();
  51086. }
  51087. // Checking if the gamepad connected event is supported (like in Firefox)
  51088. if (this._gamepadEventSupported) {
  51089. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51090. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  51091. }
  51092. else {
  51093. this._startMonitoringGamepads();
  51094. }
  51095. }
  51096. }
  51097. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  51098. get: function () {
  51099. return this._babylonGamepads;
  51100. },
  51101. enumerable: true,
  51102. configurable: true
  51103. });
  51104. GamepadManager.prototype.getGamepadByType = function (type) {
  51105. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  51106. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51107. var gamepad = _a[_i];
  51108. if (gamepad && gamepad.type === type) {
  51109. return gamepad;
  51110. }
  51111. }
  51112. return null;
  51113. };
  51114. GamepadManager.prototype.dispose = function () {
  51115. if (this._gamepadEventSupported) {
  51116. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  51117. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  51118. this._onGamepadConnectedEvent = null;
  51119. this._onGamepadDisconnectedEvent = null;
  51120. }
  51121. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51122. var gamepad = _a[_i];
  51123. gamepad.dispose();
  51124. }
  51125. this._oneGamepadConnected = false;
  51126. this._stopMonitoringGamepads();
  51127. this._babylonGamepads = [];
  51128. };
  51129. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  51130. if (!this._oneGamepadConnected) {
  51131. this._oneGamepadConnected = true;
  51132. }
  51133. var newGamepad;
  51134. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51135. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51136. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51137. }
  51138. else if (gamepad.pose) {
  51139. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51140. }
  51141. else {
  51142. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  51143. }
  51144. this._babylonGamepads[newGamepad.index] = newGamepad;
  51145. return newGamepad;
  51146. };
  51147. GamepadManager.prototype._startMonitoringGamepads = function () {
  51148. if (!this._isMonitoring) {
  51149. this._isMonitoring = true;
  51150. this._checkGamepadsStatus();
  51151. }
  51152. };
  51153. GamepadManager.prototype._stopMonitoringGamepads = function () {
  51154. this._isMonitoring = false;
  51155. };
  51156. GamepadManager.prototype._checkGamepadsStatus = function () {
  51157. var _this = this;
  51158. // Hack to be compatible Chrome
  51159. this._updateGamepadObjects();
  51160. for (var i in this._babylonGamepads) {
  51161. var gamepad = this._babylonGamepads[i];
  51162. if (!gamepad || !gamepad.isConnected) {
  51163. continue;
  51164. }
  51165. gamepad.update();
  51166. }
  51167. if (this._isMonitoring) {
  51168. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51169. }
  51170. };
  51171. // This function is called only on Chrome, which does not properly support
  51172. // connection/disconnection events and forces you to recopy again the gamepad object
  51173. GamepadManager.prototype._updateGamepadObjects = function () {
  51174. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51175. for (var i = 0; i < gamepads.length; i++) {
  51176. if (gamepads[i]) {
  51177. if (!this._babylonGamepads[gamepads[i].index]) {
  51178. var newGamepad = this._addNewGamepad(gamepads[i]);
  51179. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51180. }
  51181. else {
  51182. // Forced to copy again this object for Chrome for unknown reason
  51183. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51184. if (!this._babylonGamepads[i].isConnected) {
  51185. this._babylonGamepads[i]._isConnected = true;
  51186. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  51187. }
  51188. }
  51189. }
  51190. }
  51191. };
  51192. return GamepadManager;
  51193. }());
  51194. BABYLON.GamepadManager = GamepadManager;
  51195. })(BABYLON || (BABYLON = {}));
  51196. //# sourceMappingURL=babylon.gamepadManager.js.map
  51197. var BABYLON;
  51198. (function (BABYLON) {
  51199. var StickValues = (function () {
  51200. function StickValues(x, y) {
  51201. this.x = x;
  51202. this.y = y;
  51203. }
  51204. return StickValues;
  51205. }());
  51206. BABYLON.StickValues = StickValues;
  51207. var Gamepad = (function () {
  51208. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51209. if (leftStickX === void 0) { leftStickX = 0; }
  51210. if (leftStickY === void 0) { leftStickY = 1; }
  51211. if (rightStickX === void 0) { rightStickX = 2; }
  51212. if (rightStickY === void 0) { rightStickY = 3; }
  51213. this.id = id;
  51214. this.index = index;
  51215. this.browserGamepad = browserGamepad;
  51216. this._isConnected = true;
  51217. this.type = Gamepad.GAMEPAD;
  51218. this._leftStickAxisX = leftStickX;
  51219. this._leftStickAxisY = leftStickY;
  51220. this._rightStickAxisX = rightStickX;
  51221. this._rightStickAxisY = rightStickY;
  51222. if (this.browserGamepad.axes.length >= 2) {
  51223. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51224. }
  51225. if (this.browserGamepad.axes.length >= 4) {
  51226. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51227. }
  51228. }
  51229. Object.defineProperty(Gamepad.prototype, "isConnected", {
  51230. get: function () {
  51231. return this._isConnected;
  51232. },
  51233. enumerable: true,
  51234. configurable: true
  51235. });
  51236. Gamepad.prototype.onleftstickchanged = function (callback) {
  51237. this._onleftstickchanged = callback;
  51238. };
  51239. Gamepad.prototype.onrightstickchanged = function (callback) {
  51240. this._onrightstickchanged = callback;
  51241. };
  51242. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51243. get: function () {
  51244. return this._leftStick;
  51245. },
  51246. set: function (newValues) {
  51247. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51248. this._onleftstickchanged(newValues);
  51249. }
  51250. this._leftStick = newValues;
  51251. },
  51252. enumerable: true,
  51253. configurable: true
  51254. });
  51255. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51256. get: function () {
  51257. return this._rightStick;
  51258. },
  51259. set: function (newValues) {
  51260. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51261. this._onrightstickchanged(newValues);
  51262. }
  51263. this._rightStick = newValues;
  51264. },
  51265. enumerable: true,
  51266. configurable: true
  51267. });
  51268. Gamepad.prototype.update = function () {
  51269. if (this._leftStick) {
  51270. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51271. }
  51272. if (this._rightStick) {
  51273. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51274. }
  51275. };
  51276. Gamepad.prototype.dispose = function () {
  51277. };
  51278. Gamepad.GAMEPAD = 0;
  51279. Gamepad.GENERIC = 1;
  51280. Gamepad.XBOX = 2;
  51281. Gamepad.POSE_ENABLED = 3;
  51282. return Gamepad;
  51283. }());
  51284. BABYLON.Gamepad = Gamepad;
  51285. var GenericPad = (function (_super) {
  51286. __extends(GenericPad, _super);
  51287. function GenericPad(id, index, browserGamepad) {
  51288. var _this = _super.call(this, id, index, browserGamepad) || this;
  51289. _this.type = Gamepad.GENERIC;
  51290. _this._buttons = new Array(browserGamepad.buttons.length);
  51291. return _this;
  51292. }
  51293. GenericPad.prototype.onbuttondown = function (callback) {
  51294. this._onbuttondown = callback;
  51295. };
  51296. GenericPad.prototype.onbuttonup = function (callback) {
  51297. this._onbuttonup = callback;
  51298. };
  51299. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51300. if (newValue !== currentValue) {
  51301. if (this._onbuttondown && newValue === 1) {
  51302. this._onbuttondown(buttonIndex);
  51303. }
  51304. if (this._onbuttonup && newValue === 0) {
  51305. this._onbuttonup(buttonIndex);
  51306. }
  51307. }
  51308. return newValue;
  51309. };
  51310. GenericPad.prototype.update = function () {
  51311. _super.prototype.update.call(this);
  51312. for (var index = 0; index < this._buttons.length; index++) {
  51313. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51314. }
  51315. };
  51316. return GenericPad;
  51317. }(Gamepad));
  51318. BABYLON.GenericPad = GenericPad;
  51319. })(BABYLON || (BABYLON = {}));
  51320. //# sourceMappingURL=babylon.gamepad.js.map
  51321. var BABYLON;
  51322. (function (BABYLON) {
  51323. var Xbox360Button;
  51324. (function (Xbox360Button) {
  51325. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51326. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51327. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51328. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51329. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51330. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51331. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51332. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51333. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51334. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51335. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51336. var Xbox360Dpad;
  51337. (function (Xbox360Dpad) {
  51338. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51339. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51340. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51341. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51342. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51343. var Xbox360Pad = (function (_super) {
  51344. __extends(Xbox360Pad, _super);
  51345. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51346. if (xboxOne === void 0) { xboxOne = false; }
  51347. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51348. _this._leftTrigger = 0;
  51349. _this._rightTrigger = 0;
  51350. _this._buttonA = 0;
  51351. _this._buttonB = 0;
  51352. _this._buttonX = 0;
  51353. _this._buttonY = 0;
  51354. _this._buttonBack = 0;
  51355. _this._buttonStart = 0;
  51356. _this._buttonLB = 0;
  51357. _this._buttonRB = 0;
  51358. _this._buttonLeftStick = 0;
  51359. _this._buttonRightStick = 0;
  51360. _this._dPadUp = 0;
  51361. _this._dPadDown = 0;
  51362. _this._dPadLeft = 0;
  51363. _this._dPadRight = 0;
  51364. _this._isXboxOnePad = false;
  51365. _this.type = BABYLON.Gamepad.XBOX;
  51366. _this._isXboxOnePad = xboxOne;
  51367. return _this;
  51368. }
  51369. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51370. this._onlefttriggerchanged = callback;
  51371. };
  51372. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51373. this._onrighttriggerchanged = callback;
  51374. };
  51375. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51376. get: function () {
  51377. return this._leftTrigger;
  51378. },
  51379. set: function (newValue) {
  51380. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51381. this._onlefttriggerchanged(newValue);
  51382. }
  51383. this._leftTrigger = newValue;
  51384. },
  51385. enumerable: true,
  51386. configurable: true
  51387. });
  51388. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51389. get: function () {
  51390. return this._rightTrigger;
  51391. },
  51392. set: function (newValue) {
  51393. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51394. this._onrighttriggerchanged(newValue);
  51395. }
  51396. this._rightTrigger = newValue;
  51397. },
  51398. enumerable: true,
  51399. configurable: true
  51400. });
  51401. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51402. this._onbuttondown = callback;
  51403. };
  51404. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51405. this._onbuttonup = callback;
  51406. };
  51407. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51408. this._ondpaddown = callback;
  51409. };
  51410. Xbox360Pad.prototype.ondpadup = function (callback) {
  51411. this._ondpadup = callback;
  51412. };
  51413. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51414. if (newValue !== currentValue) {
  51415. if (this._onbuttondown && newValue === 1) {
  51416. this._onbuttondown(buttonType);
  51417. }
  51418. if (this._onbuttonup && newValue === 0) {
  51419. this._onbuttonup(buttonType);
  51420. }
  51421. }
  51422. return newValue;
  51423. };
  51424. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51425. if (newValue !== currentValue) {
  51426. if (this._ondpaddown && newValue === 1) {
  51427. this._ondpaddown(buttonType);
  51428. }
  51429. if (this._ondpadup && newValue === 0) {
  51430. this._ondpadup(buttonType);
  51431. }
  51432. }
  51433. return newValue;
  51434. };
  51435. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51436. get: function () {
  51437. return this._buttonA;
  51438. },
  51439. set: function (value) {
  51440. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51441. },
  51442. enumerable: true,
  51443. configurable: true
  51444. });
  51445. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51446. get: function () {
  51447. return this._buttonB;
  51448. },
  51449. set: function (value) {
  51450. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51451. },
  51452. enumerable: true,
  51453. configurable: true
  51454. });
  51455. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51456. get: function () {
  51457. return this._buttonX;
  51458. },
  51459. set: function (value) {
  51460. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51461. },
  51462. enumerable: true,
  51463. configurable: true
  51464. });
  51465. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51466. get: function () {
  51467. return this._buttonY;
  51468. },
  51469. set: function (value) {
  51470. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51471. },
  51472. enumerable: true,
  51473. configurable: true
  51474. });
  51475. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51476. get: function () {
  51477. return this._buttonStart;
  51478. },
  51479. set: function (value) {
  51480. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51486. get: function () {
  51487. return this._buttonBack;
  51488. },
  51489. set: function (value) {
  51490. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51496. get: function () {
  51497. return this._buttonLB;
  51498. },
  51499. set: function (value) {
  51500. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51506. get: function () {
  51507. return this._buttonRB;
  51508. },
  51509. set: function (value) {
  51510. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51511. },
  51512. enumerable: true,
  51513. configurable: true
  51514. });
  51515. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51516. get: function () {
  51517. return this._buttonLeftStick;
  51518. },
  51519. set: function (value) {
  51520. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51521. },
  51522. enumerable: true,
  51523. configurable: true
  51524. });
  51525. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51526. get: function () {
  51527. return this._buttonRightStick;
  51528. },
  51529. set: function (value) {
  51530. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51531. },
  51532. enumerable: true,
  51533. configurable: true
  51534. });
  51535. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51536. get: function () {
  51537. return this._dPadUp;
  51538. },
  51539. set: function (value) {
  51540. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51541. },
  51542. enumerable: true,
  51543. configurable: true
  51544. });
  51545. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51546. get: function () {
  51547. return this._dPadDown;
  51548. },
  51549. set: function (value) {
  51550. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51551. },
  51552. enumerable: true,
  51553. configurable: true
  51554. });
  51555. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51556. get: function () {
  51557. return this._dPadLeft;
  51558. },
  51559. set: function (value) {
  51560. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51561. },
  51562. enumerable: true,
  51563. configurable: true
  51564. });
  51565. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51566. get: function () {
  51567. return this._dPadRight;
  51568. },
  51569. set: function (value) {
  51570. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51571. },
  51572. enumerable: true,
  51573. configurable: true
  51574. });
  51575. Xbox360Pad.prototype.update = function () {
  51576. _super.prototype.update.call(this);
  51577. if (this._isXboxOnePad) {
  51578. this.buttonA = this.browserGamepad.buttons[0].value;
  51579. this.buttonB = this.browserGamepad.buttons[1].value;
  51580. this.buttonX = this.browserGamepad.buttons[2].value;
  51581. this.buttonY = this.browserGamepad.buttons[3].value;
  51582. this.buttonLB = this.browserGamepad.buttons[4].value;
  51583. this.buttonRB = this.browserGamepad.buttons[5].value;
  51584. this.leftTrigger = this.browserGamepad.axes[2];
  51585. this.rightTrigger = this.browserGamepad.axes[5];
  51586. this.buttonBack = this.browserGamepad.buttons[9].value;
  51587. this.buttonStart = this.browserGamepad.buttons[8].value;
  51588. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51589. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51590. this.dPadUp = this.browserGamepad.buttons[11].value;
  51591. this.dPadDown = this.browserGamepad.buttons[12].value;
  51592. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51593. this.dPadRight = this.browserGamepad.buttons[14].value;
  51594. }
  51595. else {
  51596. this.buttonA = this.browserGamepad.buttons[0].value;
  51597. this.buttonB = this.browserGamepad.buttons[1].value;
  51598. this.buttonX = this.browserGamepad.buttons[2].value;
  51599. this.buttonY = this.browserGamepad.buttons[3].value;
  51600. this.buttonLB = this.browserGamepad.buttons[4].value;
  51601. this.buttonRB = this.browserGamepad.buttons[5].value;
  51602. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51603. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51604. this.buttonBack = this.browserGamepad.buttons[8].value;
  51605. this.buttonStart = this.browserGamepad.buttons[9].value;
  51606. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51607. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51608. this.dPadUp = this.browserGamepad.buttons[12].value;
  51609. this.dPadDown = this.browserGamepad.buttons[13].value;
  51610. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51611. this.dPadRight = this.browserGamepad.buttons[15].value;
  51612. }
  51613. };
  51614. return Xbox360Pad;
  51615. }(BABYLON.Gamepad));
  51616. BABYLON.Xbox360Pad = Xbox360Pad;
  51617. })(BABYLON || (BABYLON = {}));
  51618. //# sourceMappingURL=babylon.xboxGamepad.js.map
  51619. var BABYLON;
  51620. (function (BABYLON) {
  51621. var PoseEnabledControllerType;
  51622. (function (PoseEnabledControllerType) {
  51623. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51624. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51625. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  51626. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  51627. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51628. var PoseEnabledControllerHelper = (function () {
  51629. function PoseEnabledControllerHelper() {
  51630. }
  51631. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51632. // Oculus Touch
  51633. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51634. return new BABYLON.OculusTouchController(vrGamepad);
  51635. }
  51636. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  51637. return new BABYLON.WindowsMotionController(vrGamepad);
  51638. }
  51639. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  51640. return new BABYLON.ViveController(vrGamepad);
  51641. }
  51642. else {
  51643. return new BABYLON.GenericController(vrGamepad);
  51644. }
  51645. };
  51646. return PoseEnabledControllerHelper;
  51647. }());
  51648. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51649. var PoseEnabledController = (function (_super) {
  51650. __extends(PoseEnabledController, _super);
  51651. function PoseEnabledController(browserGamepad) {
  51652. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  51653. _this.deviceScaleFactor = 1;
  51654. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51655. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51656. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51657. _this.position = BABYLON.Vector3.Zero();
  51658. _this.rotationQuaternion = new BABYLON.Quaternion();
  51659. _this.devicePosition = BABYLON.Vector3.Zero();
  51660. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51661. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51662. _this._calculatedRotation = new BABYLON.Quaternion();
  51663. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51664. return _this;
  51665. }
  51666. PoseEnabledController.prototype.update = function () {
  51667. _super.prototype.update.call(this);
  51668. var pose = this.browserGamepad.pose;
  51669. this.updateFromDevice(pose);
  51670. if (this._mesh) {
  51671. this._mesh.position.copyFrom(this._calculatedPosition);
  51672. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51673. }
  51674. };
  51675. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51676. if (poseData) {
  51677. this.rawPose = poseData;
  51678. if (poseData.position) {
  51679. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51680. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51681. this.devicePosition.z *= -1;
  51682. }
  51683. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51684. this._calculatedPosition.addInPlace(this.position);
  51685. }
  51686. if (poseData.orientation) {
  51687. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51688. if (this._mesh) {
  51689. if (this._mesh.getScene().useRightHandedSystem) {
  51690. this.deviceRotationQuaternion.z *= -1;
  51691. this.deviceRotationQuaternion.w *= -1;
  51692. }
  51693. else {
  51694. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51695. }
  51696. }
  51697. // if the camera is set, rotate to the camera's rotation
  51698. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51699. }
  51700. }
  51701. };
  51702. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51703. if (this._mesh) {
  51704. this._mesh.parent = undefined;
  51705. }
  51706. this._mesh = mesh;
  51707. if (this._poseControlledCamera) {
  51708. this._mesh.parent = this._poseControlledCamera;
  51709. }
  51710. if (!this._mesh.rotationQuaternion) {
  51711. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51712. }
  51713. };
  51714. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51715. this._poseControlledCamera = camera;
  51716. if (this._mesh) {
  51717. this._mesh.parent = this._poseControlledCamera;
  51718. }
  51719. };
  51720. PoseEnabledController.prototype.dispose = function () {
  51721. if (this._mesh) {
  51722. this._mesh.dispose();
  51723. }
  51724. this._mesh = undefined;
  51725. _super.prototype.dispose.call(this);
  51726. };
  51727. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51728. get: function () {
  51729. return this._mesh;
  51730. },
  51731. enumerable: true,
  51732. configurable: true
  51733. });
  51734. PoseEnabledController.prototype.getForwardRay = function (length) {
  51735. if (length === void 0) { length = 100; }
  51736. if (!this.mesh) {
  51737. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51738. }
  51739. var m = this.mesh.getWorldMatrix();
  51740. var origin = m.getTranslation();
  51741. var forward = new BABYLON.Vector3(0, 0, -1);
  51742. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51743. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51744. return new BABYLON.Ray(origin, direction, length);
  51745. };
  51746. return PoseEnabledController;
  51747. }(BABYLON.Gamepad));
  51748. BABYLON.PoseEnabledController = PoseEnabledController;
  51749. })(BABYLON || (BABYLON = {}));
  51750. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51751. var BABYLON;
  51752. (function (BABYLON) {
  51753. var WebVRController = (function (_super) {
  51754. __extends(WebVRController, _super);
  51755. function WebVRController(vrGamepad) {
  51756. var _this = _super.call(this, vrGamepad) || this;
  51757. // Observables
  51758. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51759. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51760. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51761. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51762. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51763. _this.pad = { x: 0, y: 0 };
  51764. // avoid GC, store state in a tmp object
  51765. _this._changes = {
  51766. pressChanged: false,
  51767. touchChanged: false,
  51768. valueChanged: false,
  51769. changed: false
  51770. };
  51771. _this._buttons = new Array(vrGamepad.buttons.length);
  51772. _this.hand = vrGamepad.hand;
  51773. return _this;
  51774. }
  51775. WebVRController.prototype.onButtonStateChange = function (callback) {
  51776. this._onButtonStateChange = callback;
  51777. };
  51778. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  51779. get: function () {
  51780. return this._defaultModel;
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. WebVRController.prototype.update = function () {
  51786. _super.prototype.update.call(this);
  51787. for (var index = 0; index < this._buttons.length; index++) {
  51788. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  51789. }
  51790. ;
  51791. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51792. this.pad.x = this.leftStick.x;
  51793. this.pad.y = this.leftStick.y;
  51794. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51795. }
  51796. };
  51797. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51798. if (!newState) {
  51799. newState = {
  51800. pressed: false,
  51801. touched: false,
  51802. value: 0
  51803. };
  51804. }
  51805. if (!currentState) {
  51806. this._buttons[buttonIndex] = {
  51807. pressed: newState.pressed,
  51808. touched: newState.touched,
  51809. value: newState.value
  51810. };
  51811. return;
  51812. }
  51813. this._checkChanges(newState, currentState);
  51814. if (this._changes.changed) {
  51815. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51816. this.handleButtonChange(buttonIndex, newState, this._changes);
  51817. }
  51818. this._buttons[buttonIndex].pressed = newState.pressed;
  51819. this._buttons[buttonIndex].touched = newState.touched;
  51820. // oculus triggers are never 0, thou not touched.
  51821. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51822. };
  51823. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51824. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51825. this._changes.touchChanged = newState.touched !== currentState.touched;
  51826. this._changes.valueChanged = newState.value !== currentState.value;
  51827. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51828. return this._changes;
  51829. };
  51830. WebVRController.prototype.dispose = function () {
  51831. _super.prototype.dispose.call(this);
  51832. this.onTriggerStateChangedObservable.clear();
  51833. this.onMainButtonStateChangedObservable.clear();
  51834. this.onSecondaryButtonStateChangedObservable.clear();
  51835. this.onPadStateChangedObservable.clear();
  51836. this.onPadValuesChangedObservable.clear();
  51837. };
  51838. return WebVRController;
  51839. }(BABYLON.PoseEnabledController));
  51840. BABYLON.WebVRController = WebVRController;
  51841. })(BABYLON || (BABYLON = {}));
  51842. //# sourceMappingURL=babylon.webVRController.js.map
  51843. var BABYLON;
  51844. (function (BABYLON) {
  51845. var OculusTouchController = (function (_super) {
  51846. __extends(OculusTouchController, _super);
  51847. function OculusTouchController(vrGamepad) {
  51848. var _this = _super.call(this, vrGamepad) || this;
  51849. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51850. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51851. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  51852. return _this;
  51853. }
  51854. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51855. var _this = this;
  51856. var meshName;
  51857. // Hand
  51858. if (this.hand === 'left') {
  51859. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  51860. }
  51861. else {
  51862. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  51863. }
  51864. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  51865. /*
  51866. Parent Mesh name: oculus_touch_left
  51867. - body
  51868. - trigger
  51869. - thumbstick
  51870. - grip
  51871. - button_y
  51872. - button_x
  51873. - button_enter
  51874. */
  51875. _this._defaultModel = newMeshes[1];
  51876. if (meshLoaded) {
  51877. meshLoaded(_this._defaultModel);
  51878. }
  51879. _this.attachToMesh(_this._defaultModel);
  51880. });
  51881. };
  51882. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51883. // helper getters for left and right hand.
  51884. get: function () {
  51885. if (this.hand === 'right') {
  51886. return this.onMainButtonStateChangedObservable;
  51887. }
  51888. else {
  51889. throw new Error('No A button on left hand');
  51890. }
  51891. },
  51892. enumerable: true,
  51893. configurable: true
  51894. });
  51895. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51896. get: function () {
  51897. if (this.hand === 'right') {
  51898. return this.onSecondaryButtonStateChangedObservable;
  51899. }
  51900. else {
  51901. throw new Error('No B button on left hand');
  51902. }
  51903. },
  51904. enumerable: true,
  51905. configurable: true
  51906. });
  51907. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51908. get: function () {
  51909. if (this.hand === 'left') {
  51910. return this.onMainButtonStateChangedObservable;
  51911. }
  51912. else {
  51913. throw new Error('No X button on right hand');
  51914. }
  51915. },
  51916. enumerable: true,
  51917. configurable: true
  51918. });
  51919. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51920. get: function () {
  51921. if (this.hand === 'left') {
  51922. return this.onSecondaryButtonStateChangedObservable;
  51923. }
  51924. else {
  51925. throw new Error('No Y button on right hand');
  51926. }
  51927. },
  51928. enumerable: true,
  51929. configurable: true
  51930. });
  51931. /*
  51932. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51933. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51934. 2) secondary trigger (same)
  51935. 3) A (right) X (left), touch, pressed = value
  51936. 4) B / Y
  51937. 5) thumb rest
  51938. */
  51939. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51940. var notifyObject = state; //{ state: state, changes: changes };
  51941. var triggerDirection = this.hand === 'right' ? -1 : 1;
  51942. switch (buttonIdx) {
  51943. case 0:
  51944. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51945. return;
  51946. case 1:// index trigger
  51947. if (this._defaultModel) {
  51948. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51949. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51950. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51951. }
  51952. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51953. return;
  51954. case 2:// secondary trigger
  51955. if (this._defaultModel) {
  51956. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  51957. }
  51958. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51959. return;
  51960. case 3:
  51961. if (this._defaultModel) {
  51962. if (notifyObject.pressed) {
  51963. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51964. }
  51965. else {
  51966. (this._defaultModel.getChildren()[1]).position.y = 0;
  51967. }
  51968. }
  51969. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51970. return;
  51971. case 4:
  51972. if (this._defaultModel) {
  51973. if (notifyObject.pressed) {
  51974. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51975. }
  51976. else {
  51977. (this._defaultModel.getChildren()[2]).position.y = 0;
  51978. }
  51979. }
  51980. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51981. return;
  51982. case 5:
  51983. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51984. return;
  51985. }
  51986. };
  51987. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  51988. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  51989. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  51990. return OculusTouchController;
  51991. }(BABYLON.WebVRController));
  51992. BABYLON.OculusTouchController = OculusTouchController;
  51993. })(BABYLON || (BABYLON = {}));
  51994. //# sourceMappingURL=babylon.oculusTouchController.js.map
  51995. var BABYLON;
  51996. (function (BABYLON) {
  51997. var ViveController = (function (_super) {
  51998. __extends(ViveController, _super);
  51999. function ViveController(vrGamepad) {
  52000. var _this = _super.call(this, vrGamepad) || this;
  52001. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  52002. return _this;
  52003. }
  52004. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52005. var _this = this;
  52006. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  52007. /*
  52008. Parent Mesh name: ViveWand
  52009. - body
  52010. - r_gripper
  52011. - l_gripper
  52012. - menu_button
  52013. - system_button
  52014. - trackpad
  52015. - trigger
  52016. - LED
  52017. */
  52018. _this._defaultModel = newMeshes[1];
  52019. if (meshLoaded) {
  52020. meshLoaded(_this._defaultModel);
  52021. }
  52022. _this.attachToMesh(_this._defaultModel);
  52023. });
  52024. };
  52025. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52026. get: function () {
  52027. return this.onMainButtonStateChangedObservable;
  52028. },
  52029. enumerable: true,
  52030. configurable: true
  52031. });
  52032. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52033. get: function () {
  52034. return this.onMainButtonStateChangedObservable;
  52035. },
  52036. enumerable: true,
  52037. configurable: true
  52038. });
  52039. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52040. get: function () {
  52041. return this.onSecondaryButtonStateChangedObservable;
  52042. },
  52043. enumerable: true,
  52044. configurable: true
  52045. });
  52046. /**
  52047. * Vive mapping:
  52048. * 0: touchpad
  52049. * 1: trigger
  52050. * 2: left AND right buttons
  52051. * 3: menu button
  52052. */
  52053. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52054. var notifyObject = state; //{ state: state, changes: changes };
  52055. switch (buttonIdx) {
  52056. case 0:
  52057. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52058. return;
  52059. case 1:// index trigger
  52060. if (this._defaultModel) {
  52061. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52062. }
  52063. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52064. return;
  52065. case 2:// left AND right button
  52066. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52067. return;
  52068. case 3:
  52069. if (this._defaultModel) {
  52070. if (notifyObject.pressed) {
  52071. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52072. }
  52073. else {
  52074. (this._defaultModel.getChildren()[2]).position.y = 0;
  52075. }
  52076. }
  52077. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52078. return;
  52079. }
  52080. };
  52081. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  52082. ViveController.MODEL_FILENAME = 'wand.babylon';
  52083. return ViveController;
  52084. }(BABYLON.WebVRController));
  52085. BABYLON.ViveController = ViveController;
  52086. })(BABYLON || (BABYLON = {}));
  52087. //# sourceMappingURL=babylon.viveController.js.map
  52088. var BABYLON;
  52089. (function (BABYLON) {
  52090. var GenericController = (function (_super) {
  52091. __extends(GenericController, _super);
  52092. function GenericController(vrGamepad) {
  52093. return _super.call(this, vrGamepad) || this;
  52094. }
  52095. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52096. var _this = this;
  52097. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  52098. _this._defaultModel = newMeshes[1];
  52099. if (meshLoaded) {
  52100. meshLoaded(_this._defaultModel);
  52101. }
  52102. _this.attachToMesh(_this._defaultModel);
  52103. });
  52104. };
  52105. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52106. console.log("Button id: " + buttonIdx + "state: ");
  52107. console.dir(state);
  52108. };
  52109. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  52110. GenericController.MODEL_FILENAME = 'generic.babylon';
  52111. return GenericController;
  52112. }(BABYLON.WebVRController));
  52113. BABYLON.GenericController = GenericController;
  52114. })(BABYLON || (BABYLON = {}));
  52115. //# sourceMappingURL=babylon.genericController.js.map
  52116. var BABYLON;
  52117. (function (BABYLON) {
  52118. var LoadedMeshInfo = (function () {
  52119. function LoadedMeshInfo() {
  52120. this.buttonMeshes = {};
  52121. this.axisMeshes = {};
  52122. }
  52123. return LoadedMeshInfo;
  52124. }());
  52125. var WindowsMotionController = (function (_super) {
  52126. __extends(WindowsMotionController, _super);
  52127. function WindowsMotionController(vrGamepad) {
  52128. var _this = _super.call(this, vrGamepad) || this;
  52129. _this._mapping = {
  52130. // Semantic button names
  52131. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  52132. // A mapping of the button name to glTF model node name
  52133. // that should be transformed by button value.
  52134. buttonMeshNames: {
  52135. 'trigger': 'SELECT',
  52136. 'menu': 'MENU',
  52137. 'grip': 'GRASP',
  52138. 'thumbstick': 'THUMBSTICK_PRESS',
  52139. 'trackpad': 'TOUCHPAD_PRESS'
  52140. },
  52141. // This mapping is used to translate from the Motion Controller to Babylon semantics
  52142. buttonObservableNames: {
  52143. 'trigger': 'onTriggerStateChangedObservable',
  52144. 'menu': 'onSecondaryButtonStateChangedObservable',
  52145. 'grip': 'onMainButtonStateChangedObservable',
  52146. 'thumbstick': 'onPadStateChangedObservable',
  52147. 'trackpad': 'onTrackpadChangedObservable'
  52148. },
  52149. // A mapping of the axis name to glTF model node name
  52150. // that should be transformed by axis value.
  52151. // This array mirrors the browserGamepad.axes array, such that
  52152. // the mesh corresponding to axis 0 is in this array index 0.
  52153. axisMeshNames: [
  52154. 'THUMBSTICK_X',
  52155. 'THUMBSTICK_Y',
  52156. 'TOUCHPAD_TOUCH_X',
  52157. 'TOUCHPAD_TOUCH_Y'
  52158. ]
  52159. };
  52160. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  52161. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  52162. _this._loadedMeshInfo = null;
  52163. return _this;
  52164. }
  52165. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  52166. get: function () {
  52167. return this.onTriggerStateChangedObservable;
  52168. },
  52169. enumerable: true,
  52170. configurable: true
  52171. });
  52172. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  52173. get: function () {
  52174. return this.onSecondaryButtonStateChangedObservable;
  52175. },
  52176. enumerable: true,
  52177. configurable: true
  52178. });
  52179. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  52180. get: function () {
  52181. return this.onMainButtonStateChangedObservable;
  52182. },
  52183. enumerable: true,
  52184. configurable: true
  52185. });
  52186. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  52187. get: function () {
  52188. return this.onPadStateChangedObservable;
  52189. },
  52190. enumerable: true,
  52191. configurable: true
  52192. });
  52193. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  52194. get: function () {
  52195. return this.onTrackpadChangedObservable;
  52196. },
  52197. enumerable: true,
  52198. configurable: true
  52199. });
  52200. /**
  52201. * Called once per frame by the engine.
  52202. */
  52203. WindowsMotionController.prototype.update = function () {
  52204. _super.prototype.update.call(this);
  52205. // Only need to animate axes if there is a loaded mesh
  52206. if (this._loadedMeshInfo) {
  52207. if (this.browserGamepad.axes) {
  52208. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  52209. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  52210. }
  52211. }
  52212. }
  52213. };
  52214. /**
  52215. * Called once for each button that changed state since the last frame
  52216. * @param buttonIdx Which button index changed
  52217. * @param state New state of the button
  52218. * @param changes Which properties on the state changed since last frame
  52219. */
  52220. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52221. var buttonName = this._mapping.buttons[buttonIdx];
  52222. if (!buttonName) {
  52223. return;
  52224. }
  52225. // Only emit events for buttons that we know how to map from index to name
  52226. var observable = this[this._mapping.buttonObservableNames[buttonName]];
  52227. if (observable) {
  52228. observable.notifyObservers(state);
  52229. }
  52230. this.lerpButtonTransform(buttonName, state.value);
  52231. };
  52232. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  52233. // If there is no loaded mesh, there is nothing to transform.
  52234. if (!this._loadedMeshInfo) {
  52235. return;
  52236. }
  52237. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  52238. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  52239. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  52240. };
  52241. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  52242. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  52243. if (!meshInfo) {
  52244. return;
  52245. }
  52246. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  52247. var lerpValue = axisValue * 0.5 + 0.5;
  52248. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  52249. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  52250. };
  52251. /**
  52252. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  52253. * @param scene scene in which to add meshes
  52254. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  52255. */
  52256. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  52257. var _this = this;
  52258. if (forceDefault === void 0) { forceDefault = false; }
  52259. var path;
  52260. var filename;
  52261. // Checking if GLB loader is present
  52262. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  52263. // Determine the device specific folder based on the ID suffix
  52264. var device = 'default';
  52265. if (this.id && !forceDefault) {
  52266. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  52267. device = ((match && match[0]) || device);
  52268. }
  52269. // Hand
  52270. if (this.hand === 'left') {
  52271. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  52272. }
  52273. else {
  52274. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  52275. }
  52276. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  52277. }
  52278. else {
  52279. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  52280. path = BABYLON.GenericController.MODEL_BASE_URL;
  52281. filename = BABYLON.GenericController.MODEL_FILENAME;
  52282. }
  52283. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  52284. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  52285. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  52286. if (!_this._loadedMeshInfo) {
  52287. return;
  52288. }
  52289. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  52290. _this.attachToMesh(_this._defaultModel);
  52291. if (meshLoaded) {
  52292. meshLoaded(_this._defaultModel);
  52293. }
  52294. }, null, function (scene, message) {
  52295. BABYLON.Tools.Log(message);
  52296. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  52297. if (!forceDefault) {
  52298. _this.initControllerMesh(scene, meshLoaded, true);
  52299. }
  52300. });
  52301. };
  52302. /**
  52303. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  52304. * can be transformed by button presses and axes values, based on this._mapping.
  52305. *
  52306. * @param scene scene in which the meshes exist
  52307. * @param meshes list of meshes that make up the controller model to process
  52308. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  52309. */
  52310. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  52311. var loadedMeshInfo = null;
  52312. // Create a new mesh to contain the glTF hierarchy
  52313. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  52314. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  52315. var childMesh = null;
  52316. for (var i = 0; i < meshes.length; i++) {
  52317. var mesh = meshes[i];
  52318. if (mesh.id === WindowsMotionController.MODEL_ROOT_NODE_NAME) {
  52319. // There may be a parent mesh to perform the RH to LH matrix transform.
  52320. // Exclude controller meshes from picking results
  52321. mesh.isPickable = false;
  52322. // Handle root node, attach to the new parentMesh
  52323. if (mesh.parent && mesh.parent.name === WindowsMotionController.GLTF_ROOT_TRANSFORM_NAME)
  52324. mesh = mesh.parent;
  52325. childMesh = mesh;
  52326. break;
  52327. }
  52328. }
  52329. if (childMesh) {
  52330. childMesh.setParent(parentMesh);
  52331. // Create our mesh info. Note that this method will always return non-null.
  52332. loadedMeshInfo = this.createMeshInfo(parentMesh);
  52333. }
  52334. else {
  52335. BABYLON.Tools.Warn('No node with name ' + WindowsMotionController.MODEL_ROOT_NODE_NAME + ' in model file.');
  52336. }
  52337. return loadedMeshInfo;
  52338. };
  52339. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  52340. var loadedMeshInfo = new LoadedMeshInfo();
  52341. var i;
  52342. loadedMeshInfo.rootNode = rootNode;
  52343. // Reset the caches
  52344. loadedMeshInfo.buttonMeshes = {};
  52345. loadedMeshInfo.axisMeshes = {};
  52346. // Button Meshes
  52347. for (i = 0; i < this._mapping.buttons.length; i++) {
  52348. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  52349. if (!buttonMeshName) {
  52350. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  52351. continue;
  52352. }
  52353. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  52354. if (!buttonMesh) {
  52355. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  52356. continue;
  52357. }
  52358. var buttonMeshInfo = {
  52359. index: i,
  52360. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  52361. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  52362. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  52363. };
  52364. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  52365. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  52366. }
  52367. else {
  52368. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  52369. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  52370. '(VALUE: ' + !!buttonMeshInfo.value +
  52371. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  52372. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  52373. ')');
  52374. }
  52375. }
  52376. // Axis Meshes
  52377. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  52378. var axisMeshName = this._mapping.axisMeshNames[i];
  52379. if (!axisMeshName) {
  52380. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  52381. continue;
  52382. }
  52383. var axisMesh = getChildByName(rootNode, axisMeshName);
  52384. if (!axisMesh) {
  52385. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  52386. continue;
  52387. }
  52388. var axisMeshInfo = {
  52389. index: i,
  52390. value: getImmediateChildByName(axisMesh, 'VALUE'),
  52391. min: getImmediateChildByName(axisMesh, 'MIN'),
  52392. max: getImmediateChildByName(axisMesh, 'MAX')
  52393. };
  52394. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  52395. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  52396. }
  52397. else {
  52398. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  52399. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  52400. '(VALUE: ' + !!axisMeshInfo.value +
  52401. ', MIN: ' + !!axisMeshInfo.min +
  52402. ', MAX:' + !!axisMeshInfo.max +
  52403. ')');
  52404. }
  52405. }
  52406. return loadedMeshInfo;
  52407. // Look through all children recursively. This will return null if no mesh exists with the given name.
  52408. function getChildByName(node, name) {
  52409. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  52410. }
  52411. // Look through only immediate children. This will return null if no mesh exists with the given name.
  52412. function getImmediateChildByName(node, name) {
  52413. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  52414. }
  52415. };
  52416. WindowsMotionController.prototype.dispose = function () {
  52417. _super.prototype.dispose.call(this);
  52418. this.onTrackpadChangedObservable.clear();
  52419. };
  52420. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  52421. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  52422. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  52423. WindowsMotionController.MODEL_ROOT_NODE_NAME = 'RootNode';
  52424. WindowsMotionController.GLTF_ROOT_TRANSFORM_NAME = 'root';
  52425. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  52426. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  52427. return WindowsMotionController;
  52428. }(BABYLON.WebVRController));
  52429. BABYLON.WindowsMotionController = WindowsMotionController;
  52430. })(BABYLON || (BABYLON = {}));
  52431. //# sourceMappingURL=babylon.windowsMotionController.js.map
  52432. /// <reference path="babylon.targetCamera.ts" />
  52433. var BABYLON;
  52434. (function (BABYLON) {
  52435. var FollowCamera = (function (_super) {
  52436. __extends(FollowCamera, _super);
  52437. function FollowCamera(name, position, scene, lockedTarget) {
  52438. var _this = _super.call(this, name, position, scene) || this;
  52439. _this.radius = 12;
  52440. _this.rotationOffset = 0;
  52441. _this.heightOffset = 4;
  52442. _this.cameraAcceleration = 0.05;
  52443. _this.maxCameraSpeed = 20;
  52444. _this.lockedTarget = lockedTarget;
  52445. return _this;
  52446. }
  52447. FollowCamera.prototype.getRadians = function (degrees) {
  52448. return degrees * Math.PI / 180;
  52449. };
  52450. FollowCamera.prototype.follow = function (cameraTarget) {
  52451. if (!cameraTarget)
  52452. return;
  52453. var yRotation;
  52454. if (cameraTarget.rotationQuaternion) {
  52455. var rotMatrix = new BABYLON.Matrix();
  52456. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  52457. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  52458. }
  52459. else {
  52460. yRotation = cameraTarget.rotation.y;
  52461. }
  52462. var radians = this.getRadians(this.rotationOffset) + yRotation;
  52463. var targetPosition = cameraTarget.getAbsolutePosition();
  52464. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  52465. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  52466. var dx = targetX - this.position.x;
  52467. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  52468. var dz = (targetZ) - this.position.z;
  52469. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  52470. var vy = dy * this.cameraAcceleration;
  52471. var vz = dz * this.cameraAcceleration * 2;
  52472. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  52473. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52474. }
  52475. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  52476. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52477. }
  52478. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  52479. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52480. }
  52481. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  52482. this.setTarget(targetPosition);
  52483. };
  52484. FollowCamera.prototype._checkInputs = function () {
  52485. _super.prototype._checkInputs.call(this);
  52486. this.follow(this.lockedTarget);
  52487. };
  52488. FollowCamera.prototype.getClassName = function () {
  52489. return "FollowCamera";
  52490. };
  52491. __decorate([
  52492. BABYLON.serialize()
  52493. ], FollowCamera.prototype, "radius", void 0);
  52494. __decorate([
  52495. BABYLON.serialize()
  52496. ], FollowCamera.prototype, "rotationOffset", void 0);
  52497. __decorate([
  52498. BABYLON.serialize()
  52499. ], FollowCamera.prototype, "heightOffset", void 0);
  52500. __decorate([
  52501. BABYLON.serialize()
  52502. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  52503. __decorate([
  52504. BABYLON.serialize()
  52505. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  52506. __decorate([
  52507. BABYLON.serializeAsMeshReference("lockedTargetId")
  52508. ], FollowCamera.prototype, "lockedTarget", void 0);
  52509. return FollowCamera;
  52510. }(BABYLON.TargetCamera));
  52511. BABYLON.FollowCamera = FollowCamera;
  52512. var ArcFollowCamera = (function (_super) {
  52513. __extends(ArcFollowCamera, _super);
  52514. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  52515. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  52516. _this.alpha = alpha;
  52517. _this.beta = beta;
  52518. _this.radius = radius;
  52519. _this.target = target;
  52520. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  52521. _this.follow();
  52522. return _this;
  52523. }
  52524. ArcFollowCamera.prototype.follow = function () {
  52525. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  52526. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  52527. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  52528. var targetPosition = this.target.getAbsolutePosition();
  52529. this.position = targetPosition.add(this._cartesianCoordinates);
  52530. this.setTarget(targetPosition);
  52531. };
  52532. ArcFollowCamera.prototype._checkInputs = function () {
  52533. _super.prototype._checkInputs.call(this);
  52534. this.follow();
  52535. };
  52536. ArcFollowCamera.prototype.getClassName = function () {
  52537. return "ArcFollowCamera";
  52538. };
  52539. return ArcFollowCamera;
  52540. }(BABYLON.TargetCamera));
  52541. BABYLON.ArcFollowCamera = ArcFollowCamera;
  52542. })(BABYLON || (BABYLON = {}));
  52543. //# sourceMappingURL=babylon.followCamera.js.map
  52544. /// <reference path="babylon.touchCamera.ts" />
  52545. var BABYLON;
  52546. (function (BABYLON) {
  52547. // We're mainly based on the logic defined into the FreeCamera code
  52548. var UniversalCamera = (function (_super) {
  52549. __extends(UniversalCamera, _super);
  52550. //-- end properties for backward compatibility for inputs
  52551. function UniversalCamera(name, position, scene) {
  52552. var _this = _super.call(this, name, position, scene) || this;
  52553. _this.inputs.addGamepad();
  52554. return _this;
  52555. }
  52556. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52557. //-- Begin properties for backward compatibility for inputs
  52558. get: function () {
  52559. var gamepad = this.inputs.attached["gamepad"];
  52560. if (gamepad)
  52561. return gamepad.gamepadAngularSensibility;
  52562. },
  52563. set: function (value) {
  52564. var gamepad = this.inputs.attached["gamepad"];
  52565. if (gamepad)
  52566. gamepad.gamepadAngularSensibility = value;
  52567. },
  52568. enumerable: true,
  52569. configurable: true
  52570. });
  52571. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52572. get: function () {
  52573. var gamepad = this.inputs.attached["gamepad"];
  52574. if (gamepad)
  52575. return gamepad.gamepadMoveSensibility;
  52576. },
  52577. set: function (value) {
  52578. var gamepad = this.inputs.attached["gamepad"];
  52579. if (gamepad)
  52580. gamepad.gamepadMoveSensibility = value;
  52581. },
  52582. enumerable: true,
  52583. configurable: true
  52584. });
  52585. UniversalCamera.prototype.getClassName = function () {
  52586. return "UniversalCamera";
  52587. };
  52588. return UniversalCamera;
  52589. }(BABYLON.TouchCamera));
  52590. BABYLON.UniversalCamera = UniversalCamera;
  52591. })(BABYLON || (BABYLON = {}));
  52592. //# sourceMappingURL=babylon.universalCamera.js.map
  52593. /// <reference path="babylon.universalCamera.ts" />
  52594. var BABYLON;
  52595. (function (BABYLON) {
  52596. // We're mainly based on the logic defined into the FreeCamera code
  52597. var GamepadCamera = (function (_super) {
  52598. __extends(GamepadCamera, _super);
  52599. //-- end properties for backward compatibility for inputs
  52600. function GamepadCamera(name, position, scene) {
  52601. return _super.call(this, name, position, scene) || this;
  52602. }
  52603. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52604. //-- Begin properties for backward compatibility for inputs
  52605. get: function () {
  52606. var gamepad = this.inputs.attached["gamepad"];
  52607. if (gamepad)
  52608. return gamepad.gamepadAngularSensibility;
  52609. },
  52610. set: function (value) {
  52611. var gamepad = this.inputs.attached["gamepad"];
  52612. if (gamepad)
  52613. gamepad.gamepadAngularSensibility = value;
  52614. },
  52615. enumerable: true,
  52616. configurable: true
  52617. });
  52618. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52619. get: function () {
  52620. var gamepad = this.inputs.attached["gamepad"];
  52621. if (gamepad)
  52622. return gamepad.gamepadMoveSensibility;
  52623. },
  52624. set: function (value) {
  52625. var gamepad = this.inputs.attached["gamepad"];
  52626. if (gamepad)
  52627. gamepad.gamepadMoveSensibility = value;
  52628. },
  52629. enumerable: true,
  52630. configurable: true
  52631. });
  52632. GamepadCamera.prototype.getClassName = function () {
  52633. return "GamepadCamera";
  52634. };
  52635. return GamepadCamera;
  52636. }(BABYLON.UniversalCamera));
  52637. BABYLON.GamepadCamera = GamepadCamera;
  52638. })(BABYLON || (BABYLON = {}));
  52639. //# sourceMappingURL=babylon.gamepadCamera.js.map
  52640. var BABYLON;
  52641. (function (BABYLON) {
  52642. var PostProcessRenderPipelineManager = (function () {
  52643. function PostProcessRenderPipelineManager() {
  52644. this._renderPipelines = {};
  52645. }
  52646. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  52647. this._renderPipelines[renderPipeline._name] = renderPipeline;
  52648. };
  52649. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  52650. var renderPipeline = this._renderPipelines[renderPipelineName];
  52651. if (!renderPipeline) {
  52652. return;
  52653. }
  52654. renderPipeline._attachCameras(cameras, unique);
  52655. };
  52656. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  52657. var renderPipeline = this._renderPipelines[renderPipelineName];
  52658. if (!renderPipeline) {
  52659. return;
  52660. }
  52661. renderPipeline._detachCameras(cameras);
  52662. };
  52663. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52664. var renderPipeline = this._renderPipelines[renderPipelineName];
  52665. if (!renderPipeline) {
  52666. return;
  52667. }
  52668. renderPipeline._enableEffect(renderEffectName, cameras);
  52669. };
  52670. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52671. var renderPipeline = this._renderPipelines[renderPipelineName];
  52672. if (!renderPipeline) {
  52673. return;
  52674. }
  52675. renderPipeline._disableEffect(renderEffectName, cameras);
  52676. };
  52677. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  52678. var renderPipeline = this._renderPipelines[renderPipelineName];
  52679. if (!renderPipeline) {
  52680. return;
  52681. }
  52682. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  52683. };
  52684. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  52685. var renderPipeline = this._renderPipelines[renderPipelineName];
  52686. if (!renderPipeline) {
  52687. return;
  52688. }
  52689. renderPipeline._disableDisplayOnlyPass(cameras);
  52690. };
  52691. PostProcessRenderPipelineManager.prototype.update = function () {
  52692. for (var renderPipelineName in this._renderPipelines) {
  52693. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52694. var pipeline = this._renderPipelines[renderPipelineName];
  52695. if (!pipeline.isSupported) {
  52696. pipeline.dispose();
  52697. delete this._renderPipelines[renderPipelineName];
  52698. }
  52699. else {
  52700. pipeline._update();
  52701. }
  52702. }
  52703. }
  52704. };
  52705. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  52706. for (var renderPipelineName in this._renderPipelines) {
  52707. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52708. var pipeline = this._renderPipelines[renderPipelineName];
  52709. pipeline._rebuild();
  52710. }
  52711. }
  52712. };
  52713. PostProcessRenderPipelineManager.prototype.dispose = function () {
  52714. for (var renderPipelineName in this._renderPipelines) {
  52715. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52716. var pipeline = this._renderPipelines[renderPipelineName];
  52717. pipeline.dispose();
  52718. }
  52719. }
  52720. };
  52721. return PostProcessRenderPipelineManager;
  52722. }());
  52723. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  52724. })(BABYLON || (BABYLON = {}));
  52725. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  52726. var BABYLON;
  52727. (function (BABYLON) {
  52728. var PostProcessRenderPass = (function () {
  52729. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  52730. this._enabled = true;
  52731. this._refCount = 0;
  52732. this._name = name;
  52733. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  52734. this.setRenderList(renderList);
  52735. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  52736. this._renderTexture.onAfterRenderObservable.add(afterRender);
  52737. this._scene = scene;
  52738. this._renderList = renderList;
  52739. }
  52740. // private
  52741. PostProcessRenderPass.prototype._incRefCount = function () {
  52742. if (this._refCount === 0) {
  52743. this._scene.customRenderTargets.push(this._renderTexture);
  52744. }
  52745. return ++this._refCount;
  52746. };
  52747. PostProcessRenderPass.prototype._decRefCount = function () {
  52748. this._refCount--;
  52749. if (this._refCount <= 0) {
  52750. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  52751. }
  52752. return this._refCount;
  52753. };
  52754. PostProcessRenderPass.prototype._update = function () {
  52755. this.setRenderList(this._renderList);
  52756. };
  52757. // public
  52758. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  52759. this._renderTexture.renderList = renderList;
  52760. };
  52761. PostProcessRenderPass.prototype.getRenderTexture = function () {
  52762. return this._renderTexture;
  52763. };
  52764. return PostProcessRenderPass;
  52765. }());
  52766. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  52767. })(BABYLON || (BABYLON = {}));
  52768. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  52769. var BABYLON;
  52770. (function (BABYLON) {
  52771. var PostProcessRenderEffect = (function () {
  52772. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  52773. this._engine = engine;
  52774. this._name = name;
  52775. this._singleInstance = singleInstance || true;
  52776. this._getPostProcess = getPostProcess;
  52777. this._cameras = [];
  52778. this._indicesForCamera = [];
  52779. this._postProcesses = {};
  52780. this._renderPasses = {};
  52781. this._renderEffectAsPasses = {};
  52782. }
  52783. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  52784. get: function () {
  52785. for (var index in this._postProcesses) {
  52786. if (!this._postProcesses[index].isSupported) {
  52787. return false;
  52788. }
  52789. }
  52790. return true;
  52791. },
  52792. enumerable: true,
  52793. configurable: true
  52794. });
  52795. PostProcessRenderEffect.prototype._update = function () {
  52796. for (var renderPassName in this._renderPasses) {
  52797. this._renderPasses[renderPassName]._update();
  52798. }
  52799. };
  52800. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  52801. this._renderPasses[renderPass._name] = renderPass;
  52802. this._linkParameters();
  52803. };
  52804. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  52805. delete this._renderPasses[renderPass._name];
  52806. this._linkParameters();
  52807. };
  52808. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  52809. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  52810. this._linkParameters();
  52811. };
  52812. PostProcessRenderEffect.prototype.getPass = function (passName) {
  52813. for (var renderPassName in this._renderPasses) {
  52814. if (renderPassName === passName) {
  52815. return this._renderPasses[passName];
  52816. }
  52817. }
  52818. };
  52819. PostProcessRenderEffect.prototype.emptyPasses = function () {
  52820. this._renderPasses = {};
  52821. this._linkParameters();
  52822. };
  52823. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  52824. var cameraKey;
  52825. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52826. for (var i = 0; i < _cam.length; i++) {
  52827. var camera = _cam[i];
  52828. var cameraName = camera.name;
  52829. if (this._singleInstance) {
  52830. cameraKey = 0;
  52831. }
  52832. else {
  52833. cameraKey = cameraName;
  52834. }
  52835. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  52836. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  52837. if (!this._indicesForCamera[cameraName]) {
  52838. this._indicesForCamera[cameraName] = [];
  52839. }
  52840. this._indicesForCamera[cameraName].push(index);
  52841. if (this._cameras.indexOf(camera) === -1) {
  52842. this._cameras[cameraName] = camera;
  52843. }
  52844. for (var passName in this._renderPasses) {
  52845. this._renderPasses[passName]._incRefCount();
  52846. }
  52847. }
  52848. this._linkParameters();
  52849. };
  52850. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  52851. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52852. for (var i = 0; i < _cam.length; i++) {
  52853. var camera = _cam[i];
  52854. var cameraName = camera.name;
  52855. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  52856. var index = this._cameras.indexOf(cameraName);
  52857. this._indicesForCamera.splice(index, 1);
  52858. this._cameras.splice(index, 1);
  52859. for (var passName in this._renderPasses) {
  52860. this._renderPasses[passName]._decRefCount();
  52861. }
  52862. }
  52863. };
  52864. PostProcessRenderEffect.prototype._enable = function (cameras) {
  52865. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52866. for (var i = 0; i < _cam.length; i++) {
  52867. var camera = _cam[i];
  52868. var cameraName = camera.name;
  52869. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  52870. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  52871. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  52872. }
  52873. }
  52874. for (var passName in this._renderPasses) {
  52875. this._renderPasses[passName]._incRefCount();
  52876. }
  52877. }
  52878. };
  52879. PostProcessRenderEffect.prototype._disable = function (cameras) {
  52880. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52881. for (var i = 0; i < _cam.length; i++) {
  52882. var camera = _cam[i];
  52883. var cameraName = camera.Name;
  52884. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  52885. for (var passName in this._renderPasses) {
  52886. this._renderPasses[passName]._decRefCount();
  52887. }
  52888. }
  52889. };
  52890. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  52891. if (this._singleInstance) {
  52892. return this._postProcesses[0];
  52893. }
  52894. else {
  52895. return this._postProcesses[camera.name];
  52896. }
  52897. };
  52898. PostProcessRenderEffect.prototype._linkParameters = function () {
  52899. var _this = this;
  52900. for (var index in this._postProcesses) {
  52901. if (this.applyParameters) {
  52902. this.applyParameters(this._postProcesses[index]);
  52903. }
  52904. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  52905. _this._linkTextures(effect);
  52906. });
  52907. }
  52908. };
  52909. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  52910. for (var renderPassName in this._renderPasses) {
  52911. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  52912. }
  52913. for (var renderEffectName in this._renderEffectAsPasses) {
  52914. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  52915. }
  52916. };
  52917. return PostProcessRenderEffect;
  52918. }());
  52919. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  52920. })(BABYLON || (BABYLON = {}));
  52921. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  52922. var BABYLON;
  52923. (function (BABYLON) {
  52924. var PostProcessRenderPipeline = (function () {
  52925. function PostProcessRenderPipeline(engine, name) {
  52926. this._engine = engine;
  52927. this._name = name;
  52928. this._renderEffects = new Array();
  52929. this._renderEffectsForIsolatedPass = new Array();
  52930. this._cameras = [];
  52931. }
  52932. PostProcessRenderPipeline.prototype.getClassName = function () {
  52933. return "PostProcessRenderPipeline";
  52934. };
  52935. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  52936. get: function () {
  52937. for (var renderEffectName in this._renderEffects) {
  52938. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52939. if (!this._renderEffects[renderEffectName].isSupported) {
  52940. return false;
  52941. }
  52942. }
  52943. }
  52944. return true;
  52945. },
  52946. enumerable: true,
  52947. configurable: true
  52948. });
  52949. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  52950. this._renderEffects[renderEffect._name] = renderEffect;
  52951. };
  52952. // private
  52953. PostProcessRenderPipeline.prototype._rebuild = function () {
  52954. };
  52955. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  52956. var renderEffects = this._renderEffects[renderEffectName];
  52957. if (!renderEffects) {
  52958. return;
  52959. }
  52960. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52961. };
  52962. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  52963. var renderEffects = this._renderEffects[renderEffectName];
  52964. if (!renderEffects) {
  52965. return;
  52966. }
  52967. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52968. };
  52969. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  52970. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52971. var indicesToDelete = [];
  52972. var i;
  52973. for (i = 0; i < _cam.length; i++) {
  52974. var camera = _cam[i];
  52975. var cameraName = camera.name;
  52976. if (this._cameras.indexOf(camera) === -1) {
  52977. this._cameras[cameraName] = camera;
  52978. }
  52979. else if (unique) {
  52980. indicesToDelete.push(i);
  52981. }
  52982. }
  52983. for (i = 0; i < indicesToDelete.length; i++) {
  52984. cameras.splice(indicesToDelete[i], 1);
  52985. }
  52986. for (var renderEffectName in this._renderEffects) {
  52987. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52988. this._renderEffects[renderEffectName]._attachCameras(_cam);
  52989. }
  52990. }
  52991. };
  52992. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  52993. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52994. for (var renderEffectName in this._renderEffects) {
  52995. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52996. this._renderEffects[renderEffectName]._detachCameras(_cam);
  52997. }
  52998. }
  52999. for (var i = 0; i < _cam.length; i++) {
  53000. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  53001. }
  53002. };
  53003. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  53004. var _this = this;
  53005. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53006. var pass = null;
  53007. var renderEffectName;
  53008. for (renderEffectName in this._renderEffects) {
  53009. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53010. pass = this._renderEffects[renderEffectName].getPass(passName);
  53011. if (pass != null) {
  53012. break;
  53013. }
  53014. }
  53015. }
  53016. if (pass === null) {
  53017. return;
  53018. }
  53019. for (renderEffectName in this._renderEffects) {
  53020. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53021. this._renderEffects[renderEffectName]._disable(_cam);
  53022. }
  53023. }
  53024. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  53025. for (var i = 0; i < _cam.length; i++) {
  53026. var camera = _cam[i];
  53027. var cameraName = camera.name;
  53028. 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); });
  53029. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  53030. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  53031. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  53032. }
  53033. };
  53034. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  53035. var _this = this;
  53036. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53037. for (var i = 0; i < _cam.length; i++) {
  53038. var camera = _cam[i];
  53039. var cameraName = camera.name;
  53040. 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); });
  53041. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  53042. }
  53043. for (var renderEffectName in this._renderEffects) {
  53044. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53045. this._renderEffects[renderEffectName]._enable(_cam);
  53046. }
  53047. }
  53048. };
  53049. PostProcessRenderPipeline.prototype._update = function () {
  53050. for (var renderEffectName in this._renderEffects) {
  53051. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53052. this._renderEffects[renderEffectName]._update();
  53053. }
  53054. }
  53055. for (var i = 0; i < this._cameras.length; i++) {
  53056. var cameraName = this._cameras[i].name;
  53057. if (this._renderEffectsForIsolatedPass[cameraName]) {
  53058. this._renderEffectsForIsolatedPass[cameraName]._update();
  53059. }
  53060. }
  53061. };
  53062. PostProcessRenderPipeline.prototype._reset = function () {
  53063. this._renderEffects = new Array();
  53064. this._renderEffectsForIsolatedPass = new Array();
  53065. };
  53066. PostProcessRenderPipeline.prototype.dispose = function () {
  53067. // Must be implemented by children
  53068. };
  53069. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  53070. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  53071. __decorate([
  53072. BABYLON.serialize()
  53073. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  53074. return PostProcessRenderPipeline;
  53075. }());
  53076. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  53077. })(BABYLON || (BABYLON = {}));
  53078. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  53079. var BABYLON;
  53080. (function (BABYLON) {
  53081. var DepthRenderer = (function () {
  53082. function DepthRenderer(scene, type) {
  53083. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53084. var _this = this;
  53085. this._viewMatrix = BABYLON.Matrix.Zero();
  53086. this._projectionMatrix = BABYLON.Matrix.Zero();
  53087. this._transformMatrix = BABYLON.Matrix.Zero();
  53088. this._worldViewProjection = BABYLON.Matrix.Zero();
  53089. this._scene = scene;
  53090. var engine = scene.getEngine();
  53091. // Render target
  53092. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53093. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53094. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53095. this._depthMap.refreshRate = 1;
  53096. this._depthMap.renderParticles = false;
  53097. this._depthMap.renderList = null;
  53098. // set default depth value to 1.0 (far away)
  53099. this._depthMap.onClearObservable.add(function (engine) {
  53100. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53101. });
  53102. // Custom render function
  53103. var renderSubMesh = function (subMesh) {
  53104. var mesh = subMesh.getRenderingMesh();
  53105. var scene = _this._scene;
  53106. var engine = scene.getEngine();
  53107. // Culling
  53108. engine.setState(subMesh.getMaterial().backFaceCulling);
  53109. // Managing instances
  53110. var batch = mesh._getInstancesRenderList(subMesh._id);
  53111. if (batch.mustReturn) {
  53112. return;
  53113. }
  53114. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53115. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53116. engine.enableEffect(_this._effect);
  53117. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53118. var material = subMesh.getMaterial();
  53119. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53120. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  53121. // Alpha test
  53122. if (material && material.needAlphaTesting()) {
  53123. var alphaTexture = material.getAlphaTestTexture();
  53124. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53125. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53126. }
  53127. // Bones
  53128. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53129. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53130. }
  53131. // Draw
  53132. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53133. }
  53134. };
  53135. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53136. var index;
  53137. if (depthOnlySubMeshes.length) {
  53138. engine.setColorWrite(false);
  53139. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53140. renderSubMesh(depthOnlySubMeshes.data[index]);
  53141. }
  53142. engine.setColorWrite(true);
  53143. }
  53144. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53145. renderSubMesh(opaqueSubMeshes.data[index]);
  53146. }
  53147. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53148. renderSubMesh(alphaTestSubMeshes.data[index]);
  53149. }
  53150. };
  53151. }
  53152. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53153. var material = subMesh.getMaterial();
  53154. if (material.disableDepthWrite) {
  53155. return false;
  53156. }
  53157. var defines = [];
  53158. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53159. var mesh = subMesh.getMesh();
  53160. var scene = mesh.getScene();
  53161. // Alpha test
  53162. if (material && material.needAlphaTesting()) {
  53163. defines.push("#define ALPHATEST");
  53164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53165. attribs.push(BABYLON.VertexBuffer.UVKind);
  53166. defines.push("#define UV1");
  53167. }
  53168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53169. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53170. defines.push("#define UV2");
  53171. }
  53172. }
  53173. // Bones
  53174. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53175. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53176. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53177. if (mesh.numBoneInfluencers > 4) {
  53178. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53179. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53180. }
  53181. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53182. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53183. }
  53184. else {
  53185. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53186. }
  53187. // Instances
  53188. if (useInstances) {
  53189. defines.push("#define INSTANCES");
  53190. attribs.push("world0");
  53191. attribs.push("world1");
  53192. attribs.push("world2");
  53193. attribs.push("world3");
  53194. }
  53195. // Get correct effect
  53196. var join = defines.join("\n");
  53197. if (this._cachedDefines !== join) {
  53198. this._cachedDefines = join;
  53199. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  53200. }
  53201. return this._effect.isReady();
  53202. };
  53203. DepthRenderer.prototype.getDepthMap = function () {
  53204. return this._depthMap;
  53205. };
  53206. // Methods
  53207. DepthRenderer.prototype.dispose = function () {
  53208. this._depthMap.dispose();
  53209. };
  53210. return DepthRenderer;
  53211. }());
  53212. BABYLON.DepthRenderer = DepthRenderer;
  53213. })(BABYLON || (BABYLON = {}));
  53214. //# sourceMappingURL=babylon.depthRenderer.js.map
  53215. var BABYLON;
  53216. (function (BABYLON) {
  53217. var SSAORenderingPipeline = (function (_super) {
  53218. __extends(SSAORenderingPipeline, _super);
  53219. /**
  53220. * @constructor
  53221. * @param {string} name - The rendering pipeline name
  53222. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53223. * @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 }
  53224. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53225. */
  53226. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53227. var _this = _super.call(this, scene.getEngine(), name) || this;
  53228. // Members
  53229. /**
  53230. * The PassPostProcess id in the pipeline that contains the original scene color
  53231. * @type {string}
  53232. */
  53233. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53234. /**
  53235. * The SSAO PostProcess id in the pipeline
  53236. * @type {string}
  53237. */
  53238. _this.SSAORenderEffect = "SSAORenderEffect";
  53239. /**
  53240. * The horizontal blur PostProcess id in the pipeline
  53241. * @type {string}
  53242. */
  53243. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53244. /**
  53245. * The vertical blur PostProcess id in the pipeline
  53246. * @type {string}
  53247. */
  53248. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53249. /**
  53250. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53251. * @type {string}
  53252. */
  53253. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53254. /**
  53255. * The output strength of the SSAO post-process. Default value is 1.0.
  53256. * @type {number}
  53257. */
  53258. _this.totalStrength = 1.0;
  53259. /**
  53260. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53261. * @type {number}
  53262. */
  53263. _this.radius = 0.0001;
  53264. /**
  53265. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53266. * Must not be equal to fallOff and superior to fallOff.
  53267. * Default value is 0.975
  53268. * @type {number}
  53269. */
  53270. _this.area = 0.0075;
  53271. /**
  53272. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53273. * Must not be equal to area and inferior to area.
  53274. * Default value is 0.0
  53275. * @type {number}
  53276. */
  53277. _this.fallOff = 0.000001;
  53278. /**
  53279. * The base color of the SSAO post-process
  53280. * The final result is "base + ssao" between [0, 1]
  53281. * @type {number}
  53282. */
  53283. _this.base = 0.5;
  53284. _this._firstUpdate = true;
  53285. _this._scene = scene;
  53286. // Set up assets
  53287. _this._createRandomTexture();
  53288. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53289. var ssaoRatio = ratio.ssaoRatio || ratio;
  53290. var combineRatio = ratio.combineRatio || ratio;
  53291. _this._ratio = {
  53292. ssaoRatio: ssaoRatio,
  53293. combineRatio: combineRatio
  53294. };
  53295. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53296. _this._createSSAOPostProcess(ssaoRatio);
  53297. _this._createBlurPostProcess(ssaoRatio);
  53298. _this._createSSAOCombinePostProcess(combineRatio);
  53299. // Set up pipeline
  53300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53301. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53302. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53303. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53304. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53305. // Finish
  53306. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53307. if (cameras)
  53308. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53309. return _this;
  53310. }
  53311. // Public Methods
  53312. /**
  53313. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53314. */
  53315. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53316. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53317. for (var i = 0; i < this._scene.cameras.length; i++) {
  53318. var camera = this._scene.cameras[i];
  53319. this._originalColorPostProcess.dispose(camera);
  53320. this._ssaoPostProcess.dispose(camera);
  53321. this._blurHPostProcess.dispose(camera);
  53322. this._blurVPostProcess.dispose(camera);
  53323. this._ssaoCombinePostProcess.dispose(camera);
  53324. }
  53325. this._randomTexture.dispose();
  53326. if (disableDepthRender)
  53327. this._scene.disableDepthRenderer();
  53328. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53329. _super.prototype.dispose.call(this);
  53330. };
  53331. // Private Methods
  53332. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53333. var _this = this;
  53334. /*
  53335. var samplerOffsets = [
  53336. -8.0, -6.0, -4.0, -2.0,
  53337. 0.0,
  53338. 2.0, 4.0, 6.0, 8.0
  53339. ];
  53340. */
  53341. var samples = 16;
  53342. var samplerOffsets = [];
  53343. for (var i = -8; i < 8; i++) {
  53344. samplerOffsets.push(i * 2);
  53345. }
  53346. 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");
  53347. this._blurHPostProcess.onApply = function (effect) {
  53348. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53349. effect.setTexture("depthSampler", _this._depthTexture);
  53350. if (_this._firstUpdate) {
  53351. effect.setArray("samplerOffsets", samplerOffsets);
  53352. }
  53353. };
  53354. 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");
  53355. this._blurVPostProcess.onApply = function (effect) {
  53356. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53357. effect.setTexture("depthSampler", _this._depthTexture);
  53358. if (_this._firstUpdate) {
  53359. effect.setArray("samplerOffsets", samplerOffsets);
  53360. _this._firstUpdate = false;
  53361. }
  53362. };
  53363. };
  53364. SSAORenderingPipeline.prototype._rebuild = function () {
  53365. this._firstUpdate = true;
  53366. _super.prototype._rebuild.call(this);
  53367. };
  53368. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53369. var _this = this;
  53370. var numSamples = 16;
  53371. var sampleSphere = [
  53372. 0.5381, 0.1856, -0.4319,
  53373. 0.1379, 0.2486, 0.4430,
  53374. 0.3371, 0.5679, -0.0057,
  53375. -0.6999, -0.0451, -0.0019,
  53376. 0.0689, -0.1598, -0.8547,
  53377. 0.0560, 0.0069, -0.1843,
  53378. -0.0146, 0.1402, 0.0762,
  53379. 0.0100, -0.1924, -0.0344,
  53380. -0.3577, -0.5301, -0.4358,
  53381. -0.3169, 0.1063, 0.0158,
  53382. 0.0103, -0.5869, 0.0046,
  53383. -0.0897, -0.4940, 0.3287,
  53384. 0.7119, -0.0154, -0.0918,
  53385. -0.0533, 0.0596, -0.5411,
  53386. 0.0352, -0.0631, 0.5460,
  53387. -0.4776, 0.2847, -0.0271
  53388. ];
  53389. var samplesFactor = 1.0 / numSamples;
  53390. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53391. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53392. "area", "fallOff", "base", "range", "viewport"
  53393. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53394. var viewport = new BABYLON.Vector2(0, 0);
  53395. this._ssaoPostProcess.onApply = function (effect) {
  53396. if (_this._firstUpdate) {
  53397. effect.setArray3("sampleSphere", sampleSphere);
  53398. effect.setFloat("samplesFactor", samplesFactor);
  53399. effect.setFloat("randTextureTiles", 4.0);
  53400. }
  53401. effect.setFloat("totalStrength", _this.totalStrength);
  53402. effect.setFloat("radius", _this.radius);
  53403. effect.setFloat("area", _this.area);
  53404. effect.setFloat("fallOff", _this.fallOff);
  53405. effect.setFloat("base", _this.base);
  53406. effect.setTexture("textureSampler", _this._depthTexture);
  53407. effect.setTexture("randomSampler", _this._randomTexture);
  53408. };
  53409. };
  53410. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53411. var _this = this;
  53412. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53413. this._ssaoCombinePostProcess.onApply = function (effect) {
  53414. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53415. };
  53416. };
  53417. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53418. var size = 512;
  53419. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53420. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53421. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53422. var context = this._randomTexture.getContext();
  53423. var rand = function (min, max) {
  53424. return Math.random() * (max - min) + min;
  53425. };
  53426. var randVector = BABYLON.Vector3.Zero();
  53427. for (var x = 0; x < size; x++) {
  53428. for (var y = 0; y < size; y++) {
  53429. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53430. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53431. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53432. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53433. context.fillRect(x, y, 1, 1);
  53434. }
  53435. }
  53436. this._randomTexture.update(false);
  53437. };
  53438. __decorate([
  53439. BABYLON.serialize()
  53440. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53441. __decorate([
  53442. BABYLON.serialize()
  53443. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53444. __decorate([
  53445. BABYLON.serialize()
  53446. ], SSAORenderingPipeline.prototype, "area", void 0);
  53447. __decorate([
  53448. BABYLON.serialize()
  53449. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53450. __decorate([
  53451. BABYLON.serialize()
  53452. ], SSAORenderingPipeline.prototype, "base", void 0);
  53453. __decorate([
  53454. BABYLON.serialize()
  53455. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53456. return SSAORenderingPipeline;
  53457. }(BABYLON.PostProcessRenderPipeline));
  53458. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53459. })(BABYLON || (BABYLON = {}));
  53460. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53461. var BABYLON;
  53462. (function (BABYLON) {
  53463. var SSAO2RenderingPipeline = (function (_super) {
  53464. __extends(SSAO2RenderingPipeline, _super);
  53465. /**
  53466. * @constructor
  53467. * @param {string} name - The rendering pipeline name
  53468. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53469. * @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 }
  53470. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53471. */
  53472. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  53473. var _this = _super.call(this, scene.getEngine(), name) || this;
  53474. // Members
  53475. /**
  53476. * The PassPostProcess id in the pipeline that contains the original scene color
  53477. * @type {string}
  53478. */
  53479. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53480. /**
  53481. * The SSAO PostProcess id in the pipeline
  53482. * @type {string}
  53483. */
  53484. _this.SSAORenderEffect = "SSAORenderEffect";
  53485. /**
  53486. * The horizontal blur PostProcess id in the pipeline
  53487. * @type {string}
  53488. */
  53489. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53490. /**
  53491. * The vertical blur PostProcess id in the pipeline
  53492. * @type {string}
  53493. */
  53494. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53495. /**
  53496. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53497. * @type {string}
  53498. */
  53499. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53500. /**
  53501. * The output strength of the SSAO post-process. Default value is 1.0.
  53502. * @type {number}
  53503. */
  53504. _this.totalStrength = 1.0;
  53505. /**
  53506. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  53507. * @type {number}
  53508. */
  53509. _this.maxZ = 100.0;
  53510. /**
  53511. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  53512. * @type {number}
  53513. */
  53514. _this.minZAspect = 0.2;
  53515. /**
  53516. * Number of samples used for the SSAO calculations. Default value is 8
  53517. * @type {number}
  53518. */
  53519. _this._samples = 8;
  53520. /**
  53521. * Are we using bilateral blur ?
  53522. * @type {boolean}
  53523. */
  53524. _this._expensiveBlur = true;
  53525. /**
  53526. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  53527. * @type {number}
  53528. */
  53529. _this.radius = 2.0;
  53530. /**
  53531. * The base color of the SSAO post-process
  53532. * The final result is "base + ssao" between [0, 1]
  53533. * @type {number}
  53534. */
  53535. _this.base = 0.1;
  53536. _this._firstUpdate = true;
  53537. _this._scene = scene;
  53538. if (!_this.isSupported) {
  53539. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  53540. return _this;
  53541. }
  53542. var ssaoRatio = ratio.ssaoRatio || ratio;
  53543. var blurRatio = ratio.blurRatio || ratio;
  53544. _this._ratio = {
  53545. ssaoRatio: ssaoRatio,
  53546. blurRatio: blurRatio
  53547. };
  53548. // Set up assets
  53549. _this._createRandomTexture();
  53550. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  53551. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  53552. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53553. _this._createSSAOPostProcess(1.0);
  53554. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  53555. _this._createSSAOCombinePostProcess(blurRatio);
  53556. // Set up pipeline
  53557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53559. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53561. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53562. // Finish
  53563. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53564. if (cameras)
  53565. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53566. return _this;
  53567. }
  53568. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  53569. get: function () {
  53570. return this._samples;
  53571. },
  53572. set: function (n) {
  53573. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  53574. this._samples = n;
  53575. this._sampleSphere = this._generateHemisphere();
  53576. this._firstUpdate = true;
  53577. },
  53578. enumerable: true,
  53579. configurable: true
  53580. });
  53581. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  53582. get: function () {
  53583. return this._expensiveBlur;
  53584. },
  53585. set: function (b) {
  53586. 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"]);
  53587. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  53588. this._expensiveBlur = b;
  53589. this._firstUpdate = true;
  53590. },
  53591. enumerable: true,
  53592. configurable: true
  53593. });
  53594. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  53595. /**
  53596. * Support test.
  53597. * @type {boolean}
  53598. */
  53599. get: function () {
  53600. var engine = BABYLON.Engine.LastCreatedEngine;
  53601. return engine.getCaps().drawBuffersExtension;
  53602. },
  53603. enumerable: true,
  53604. configurable: true
  53605. });
  53606. // Public Methods
  53607. /**
  53608. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53609. */
  53610. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  53611. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  53612. for (var i = 0; i < this._scene.cameras.length; i++) {
  53613. var camera = this._scene.cameras[i];
  53614. this._originalColorPostProcess.dispose(camera);
  53615. this._ssaoPostProcess.dispose(camera);
  53616. this._blurHPostProcess.dispose(camera);
  53617. this._blurVPostProcess.dispose(camera);
  53618. this._ssaoCombinePostProcess.dispose(camera);
  53619. }
  53620. this._randomTexture.dispose();
  53621. if (disableGeometryBufferRenderer)
  53622. this._scene.disableGeometryBufferRenderer();
  53623. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53624. _super.prototype.dispose.call(this);
  53625. };
  53626. // Private Methods
  53627. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  53628. var _this = this;
  53629. var samples = 16;
  53630. this._samplerOffsets = [];
  53631. var expensive = this.expensiveBlur;
  53632. for (var i = -8; i < 8; i++) {
  53633. this._samplerOffsets.push(i * 2 + 0.5);
  53634. }
  53635. 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");
  53636. this._blurHPostProcess.onApply = function (effect) {
  53637. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53638. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53639. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53640. effect.setFloat("radius", _this.radius);
  53641. effect.setTexture("depthSampler", _this._depthTexture);
  53642. if (_this._firstUpdate) {
  53643. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53644. }
  53645. };
  53646. 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");
  53647. this._blurVPostProcess.onApply = function (effect) {
  53648. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53649. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53650. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53651. effect.setFloat("radius", _this.radius);
  53652. effect.setTexture("depthSampler", _this._depthTexture);
  53653. if (_this._firstUpdate) {
  53654. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53655. _this._firstUpdate = false;
  53656. }
  53657. };
  53658. };
  53659. SSAO2RenderingPipeline.prototype._rebuild = function () {
  53660. this._firstUpdate = true;
  53661. _super.prototype._rebuild.call(this);
  53662. };
  53663. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  53664. var numSamples = this.samples;
  53665. var result = [];
  53666. var vector, scale;
  53667. var rand = function (min, max) {
  53668. return Math.random() * (max - min) + min;
  53669. };
  53670. var lerp = function (start, end, percent) {
  53671. return (start + percent * (end - start));
  53672. };
  53673. var i = 0;
  53674. var normal = new BABYLON.Vector3(0, 0, 1);
  53675. while (i < numSamples) {
  53676. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  53677. vector.normalize();
  53678. scale = i / numSamples;
  53679. scale = lerp(0.1, 1.0, scale * scale);
  53680. vector.scaleInPlace(scale);
  53681. result.push(vector.x, vector.y, vector.z);
  53682. i++;
  53683. }
  53684. return result;
  53685. };
  53686. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53687. var _this = this;
  53688. var numSamples = this.samples;
  53689. this._sampleSphere = this._generateHemisphere();
  53690. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  53691. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53692. "base", "range", "projection", "near", "far", "texelSize",
  53693. "xViewport", "yViewport", "maxZ", "minZAspect"
  53694. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53695. this._ssaoPostProcess.onApply = function (effect) {
  53696. if (_this._firstUpdate) {
  53697. effect.setArray3("sampleSphere", _this._sampleSphere);
  53698. effect.setFloat("randTextureTiles", 4.0);
  53699. }
  53700. effect.setFloat("samplesFactor", 1 / _this.samples);
  53701. effect.setFloat("totalStrength", _this.totalStrength);
  53702. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  53703. effect.setFloat("radius", _this.radius);
  53704. effect.setFloat("maxZ", _this.maxZ);
  53705. effect.setFloat("minZAspect", _this.minZAspect);
  53706. effect.setFloat("base", _this.base);
  53707. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53708. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53709. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  53710. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  53711. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  53712. effect.setTexture("textureSampler", _this._depthTexture);
  53713. effect.setTexture("normalSampler", _this._normalTexture);
  53714. effect.setTexture("randomSampler", _this._randomTexture);
  53715. };
  53716. };
  53717. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53718. var _this = this;
  53719. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53720. this._ssaoCombinePostProcess.onApply = function (effect) {
  53721. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53722. };
  53723. };
  53724. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  53725. var size = 512;
  53726. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53727. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53728. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53729. var context = this._randomTexture.getContext();
  53730. var rand = function (min, max) {
  53731. return Math.random() * (max - min) + min;
  53732. };
  53733. var randVector = BABYLON.Vector3.Zero();
  53734. for (var x = 0; x < size; x++) {
  53735. for (var y = 0; y < size; y++) {
  53736. randVector.x = rand(0.0, 1.0);
  53737. randVector.y = rand(0.0, 1.0);
  53738. randVector.z = 0.0;
  53739. randVector.normalize();
  53740. randVector.scaleInPlace(255);
  53741. randVector.x = Math.floor(randVector.x);
  53742. randVector.y = Math.floor(randVector.y);
  53743. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53744. context.fillRect(x, y, 1, 1);
  53745. }
  53746. }
  53747. this._randomTexture.update(false);
  53748. };
  53749. __decorate([
  53750. BABYLON.serialize()
  53751. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  53752. __decorate([
  53753. BABYLON.serialize()
  53754. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  53755. __decorate([
  53756. BABYLON.serialize()
  53757. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  53758. __decorate([
  53759. BABYLON.serialize("samples")
  53760. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  53761. __decorate([
  53762. BABYLON.serialize("expensiveBlur")
  53763. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  53764. __decorate([
  53765. BABYLON.serialize()
  53766. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  53767. __decorate([
  53768. BABYLON.serialize()
  53769. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  53770. __decorate([
  53771. BABYLON.serialize()
  53772. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  53773. return SSAO2RenderingPipeline;
  53774. }(BABYLON.PostProcessRenderPipeline));
  53775. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  53776. })(BABYLON || (BABYLON = {}));
  53777. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  53778. // BABYLON.JS Chromatic Aberration GLSL Shader
  53779. // Author: Olivier Guyot
  53780. // Separates very slightly R, G and B colors on the edges of the screen
  53781. // Inspired by Francois Tarlier & Martins Upitis
  53782. var BABYLON;
  53783. (function (BABYLON) {
  53784. var LensRenderingPipeline = (function (_super) {
  53785. __extends(LensRenderingPipeline, _super);
  53786. /**
  53787. * @constructor
  53788. *
  53789. * Effect parameters are as follow:
  53790. * {
  53791. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53792. * edge_blur: number; // from 0 to x (1 for realism)
  53793. * distortion: number; // from 0 to x (1 for realism)
  53794. * grain_amount: number; // from 0 to 1
  53795. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53796. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53797. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53798. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53799. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53800. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53801. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53802. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53803. * }
  53804. * Note: if an effect parameter is unset, effect is disabled
  53805. *
  53806. * @param {string} name - The rendering pipeline name
  53807. * @param {object} parameters - An object containing all parameters (see above)
  53808. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53809. * @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)
  53810. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53811. */
  53812. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53813. if (ratio === void 0) { ratio = 1.0; }
  53814. var _this = _super.call(this, scene.getEngine(), name) || this;
  53815. // Lens effects can be of the following:
  53816. // - chromatic aberration (slight shift of RGB colors)
  53817. // - blur on the edge of the lens
  53818. // - lens distortion
  53819. // - depth-of-field blur & highlights enhancing
  53820. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  53821. // - grain effect (noise or custom texture)
  53822. // Two additional texture samplers are needed:
  53823. // - depth map (for depth-of-field)
  53824. // - grain texture
  53825. /**
  53826. * The chromatic aberration PostProcess id in the pipeline
  53827. * @type {string}
  53828. */
  53829. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  53830. /**
  53831. * The highlights enhancing PostProcess id in the pipeline
  53832. * @type {string}
  53833. */
  53834. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  53835. /**
  53836. * The depth-of-field PostProcess id in the pipeline
  53837. * @type {string}
  53838. */
  53839. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  53840. _this._scene = scene;
  53841. // Fetch texture samplers
  53842. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53843. if (parameters.grain_texture) {
  53844. _this._grainTexture = parameters.grain_texture;
  53845. }
  53846. else {
  53847. _this._createGrainTexture();
  53848. }
  53849. // save parameters
  53850. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  53851. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  53852. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  53853. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  53854. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  53855. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  53856. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  53857. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  53858. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  53859. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  53860. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  53861. // Create effects
  53862. _this._createChromaticAberrationPostProcess(ratio);
  53863. _this._createHighlightsPostProcess(ratio);
  53864. _this._createDepthOfFieldPostProcess(ratio / 4);
  53865. // Set up pipeline
  53866. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  53867. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  53868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  53869. if (_this._highlightsGain === -1) {
  53870. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  53871. }
  53872. // Finish
  53873. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53874. if (cameras) {
  53875. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53876. }
  53877. return _this;
  53878. }
  53879. // public methods (self explanatory)
  53880. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  53881. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  53882. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  53883. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  53884. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  53885. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  53886. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  53887. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  53888. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  53889. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  53890. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  53891. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  53892. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  53893. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  53894. };
  53895. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  53896. this._highlightsPostProcess.updateEffect();
  53897. };
  53898. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  53899. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  53900. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  53901. this._highlightsGain = amount;
  53902. };
  53903. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  53904. if (this._highlightsGain === -1) {
  53905. this._highlightsGain = 1.0;
  53906. }
  53907. this._highlightsThreshold = amount;
  53908. };
  53909. LensRenderingPipeline.prototype.disableHighlights = function () {
  53910. this._highlightsGain = -1;
  53911. };
  53912. /**
  53913. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53914. */
  53915. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53916. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53917. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53918. this._chromaticAberrationPostProcess = undefined;
  53919. this._highlightsPostProcess = undefined;
  53920. this._depthOfFieldPostProcess = undefined;
  53921. this._grainTexture.dispose();
  53922. if (disableDepthRender)
  53923. this._scene.disableDepthRenderer();
  53924. };
  53925. // colors shifting and distortion
  53926. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53927. var _this = this;
  53928. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53929. [], // samplers
  53930. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53931. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53932. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53933. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53934. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53935. };
  53936. };
  53937. // highlights enhancing
  53938. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53939. var _this = this;
  53940. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53941. [], // samplers
  53942. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53943. this._highlightsPostProcess.onApply = function (effect) {
  53944. effect.setFloat('gain', _this._highlightsGain);
  53945. effect.setFloat('threshold', _this._highlightsThreshold);
  53946. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53947. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53948. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53949. };
  53950. };
  53951. // colors shifting and distortion
  53952. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53953. var _this = this;
  53954. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53955. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53956. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53957. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53958. this._depthOfFieldPostProcess.onApply = function (effect) {
  53959. effect.setTexture("depthSampler", _this._depthTexture);
  53960. effect.setTexture("grainSampler", _this._grainTexture);
  53961. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53962. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53963. effect.setFloat('grain_amount', _this._grainAmount);
  53964. effect.setBool('blur_noise', _this._blurNoise);
  53965. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53966. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53967. effect.setFloat('distortion', _this._distortion);
  53968. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53969. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53970. effect.setFloat('aperture', _this._dofAperture);
  53971. effect.setFloat('darken', _this._dofDarken);
  53972. effect.setFloat('edge_blur', _this._edgeBlur);
  53973. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53974. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53975. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53976. };
  53977. };
  53978. // creates a black and white random noise texture, 512x512
  53979. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53980. var size = 512;
  53981. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53982. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53983. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53984. var context = this._grainTexture.getContext();
  53985. var rand = function (min, max) {
  53986. return Math.random() * (max - min) + min;
  53987. };
  53988. var value;
  53989. for (var x = 0; x < size; x++) {
  53990. for (var y = 0; y < size; y++) {
  53991. value = Math.floor(rand(0.42, 0.58) * 255);
  53992. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53993. context.fillRect(x, y, 1, 1);
  53994. }
  53995. }
  53996. this._grainTexture.update(false);
  53997. };
  53998. return LensRenderingPipeline;
  53999. }(BABYLON.PostProcessRenderPipeline));
  54000. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54001. })(BABYLON || (BABYLON = {}));
  54002. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54003. var BABYLON;
  54004. (function (BABYLON) {
  54005. var StandardRenderingPipeline = (function (_super) {
  54006. __extends(StandardRenderingPipeline, _super);
  54007. /**
  54008. * @constructor
  54009. * @param {string} name - The rendering pipeline name
  54010. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54011. * @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)
  54012. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54013. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54014. */
  54015. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54016. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54017. var _this = _super.call(this, scene.getEngine(), name) || this;
  54018. _this.downSampleX4PostProcess = null;
  54019. _this.brightPassPostProcess = null;
  54020. _this.blurHPostProcesses = [];
  54021. _this.blurVPostProcesses = [];
  54022. _this.textureAdderPostProcess = null;
  54023. _this.volumetricLightPostProcess = null;
  54024. _this.volumetricLightSmoothXPostProcess = null;
  54025. _this.volumetricLightSmoothYPostProcess = null;
  54026. _this.volumetricLightMergePostProces = null;
  54027. _this.volumetricLightFinalPostProcess = null;
  54028. _this.luminancePostProcess = null;
  54029. _this.luminanceDownSamplePostProcesses = [];
  54030. _this.hdrPostProcess = null;
  54031. _this.textureAdderFinalPostProcess = null;
  54032. _this.lensFlareFinalPostProcess = null;
  54033. _this.hdrFinalPostProcess = null;
  54034. _this.lensFlarePostProcess = null;
  54035. _this.lensFlareComposePostProcess = null;
  54036. _this.motionBlurPostProcess = null;
  54037. _this.depthOfFieldPostProcess = null;
  54038. // Values
  54039. _this.brightThreshold = 1.0;
  54040. _this.blurWidth = 512.0;
  54041. _this.horizontalBlur = false;
  54042. _this.exposure = 1.0;
  54043. _this.lensTexture = null;
  54044. _this.volumetricLightCoefficient = 0.2;
  54045. _this.volumetricLightPower = 4.0;
  54046. _this.volumetricLightBlurScale = 64.0;
  54047. _this.sourceLight = null;
  54048. _this.hdrMinimumLuminance = 1.0;
  54049. _this.hdrDecreaseRate = 0.5;
  54050. _this.hdrIncreaseRate = 0.5;
  54051. _this.lensColorTexture = null;
  54052. _this.lensFlareStrength = 20.0;
  54053. _this.lensFlareGhostDispersal = 1.4;
  54054. _this.lensFlareHaloWidth = 0.7;
  54055. _this.lensFlareDistortionStrength = 16.0;
  54056. _this.lensStarTexture = null;
  54057. _this.lensFlareDirtTexture = null;
  54058. _this.depthOfFieldDistance = 10.0;
  54059. _this.depthOfFieldBlurWidth = 64.0;
  54060. _this.motionStrength = 1.0;
  54061. // IAnimatable
  54062. _this.animations = [];
  54063. _this._currentDepthOfFieldSource = null;
  54064. _this._hdrCurrentLuminance = 1.0;
  54065. // Getters and setters
  54066. _this._bloomEnabled = true;
  54067. _this._depthOfFieldEnabled = false;
  54068. _this._vlsEnabled = false;
  54069. _this._lensFlareEnabled = false;
  54070. _this._hdrEnabled = false;
  54071. _this._motionBlurEnabled = false;
  54072. _this._motionBlurSamples = 64.0;
  54073. _this._volumetricLightStepsCount = 50.0;
  54074. _this._cameras = cameras || [];
  54075. // Initialize
  54076. _this._scene = scene;
  54077. _this._basePostProcess = originalPostProcess;
  54078. _this._ratio = ratio;
  54079. // Misc
  54080. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54081. // Finish
  54082. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54083. _this._buildPipeline();
  54084. return _this;
  54085. }
  54086. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  54087. get: function () {
  54088. return this._bloomEnabled;
  54089. },
  54090. set: function (enabled) {
  54091. if (this._bloomEnabled === enabled) {
  54092. return;
  54093. }
  54094. this._bloomEnabled = enabled;
  54095. this._buildPipeline();
  54096. },
  54097. enumerable: true,
  54098. configurable: true
  54099. });
  54100. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54101. get: function () {
  54102. return this._depthOfFieldEnabled;
  54103. },
  54104. set: function (enabled) {
  54105. if (this._depthOfFieldEnabled === enabled) {
  54106. return;
  54107. }
  54108. this._depthOfFieldEnabled = enabled;
  54109. this._buildPipeline();
  54110. },
  54111. enumerable: true,
  54112. configurable: true
  54113. });
  54114. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54115. get: function () {
  54116. return this._lensFlareEnabled;
  54117. },
  54118. set: function (enabled) {
  54119. if (this._lensFlareEnabled === enabled) {
  54120. return;
  54121. }
  54122. this._lensFlareEnabled = enabled;
  54123. this._buildPipeline();
  54124. },
  54125. enumerable: true,
  54126. configurable: true
  54127. });
  54128. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  54129. get: function () {
  54130. return this._hdrEnabled;
  54131. },
  54132. set: function (enabled) {
  54133. if (this._hdrEnabled === enabled) {
  54134. return;
  54135. }
  54136. this._hdrEnabled = enabled;
  54137. this._buildPipeline();
  54138. },
  54139. enumerable: true,
  54140. configurable: true
  54141. });
  54142. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  54143. get: function () {
  54144. return this._vlsEnabled;
  54145. },
  54146. set: function (enabled) {
  54147. if (this._vlsEnabled === enabled) {
  54148. return;
  54149. }
  54150. if (enabled) {
  54151. var geometry = this._scene.enableGeometryBufferRenderer();
  54152. if (!geometry) {
  54153. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  54154. return;
  54155. }
  54156. }
  54157. this._vlsEnabled = enabled;
  54158. this._buildPipeline();
  54159. },
  54160. enumerable: true,
  54161. configurable: true
  54162. });
  54163. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  54164. get: function () {
  54165. return this._motionBlurEnabled;
  54166. },
  54167. set: function (enabled) {
  54168. if (this._motionBlurEnabled === enabled) {
  54169. return;
  54170. }
  54171. this._motionBlurEnabled = enabled;
  54172. this._buildPipeline();
  54173. },
  54174. enumerable: true,
  54175. configurable: true
  54176. });
  54177. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  54178. get: function () {
  54179. return this._volumetricLightStepsCount;
  54180. },
  54181. set: function (count) {
  54182. if (this.volumetricLightPostProcess) {
  54183. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  54184. }
  54185. this._volumetricLightStepsCount = count;
  54186. },
  54187. enumerable: true,
  54188. configurable: true
  54189. });
  54190. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  54191. get: function () {
  54192. return this._motionBlurSamples;
  54193. },
  54194. set: function (samples) {
  54195. if (this.motionBlurPostProcess) {
  54196. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  54197. }
  54198. this._motionBlurSamples = samples;
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. StandardRenderingPipeline.prototype._buildPipeline = function () {
  54204. var _this = this;
  54205. var ratio = this._ratio;
  54206. var scene = this._scene;
  54207. this._disposePostProcesses();
  54208. this._reset();
  54209. // Create pass post-process
  54210. if (!this._basePostProcess) {
  54211. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  54212. this.originalPostProcess.onApply = function (effect) {
  54213. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  54214. };
  54215. }
  54216. else {
  54217. this.originalPostProcess = this._basePostProcess;
  54218. }
  54219. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54220. this._currentDepthOfFieldSource = this.originalPostProcess;
  54221. if (this._vlsEnabled) {
  54222. // Create volumetric light
  54223. this._createVolumetricLightPostProcess(scene, ratio);
  54224. // Create volumetric light final post-process
  54225. 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);
  54226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  54227. }
  54228. if (this._bloomEnabled) {
  54229. // Create down sample X4 post-process
  54230. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54231. // Create bright pass post-process
  54232. this._createBrightPassPostProcess(scene, ratio / 2);
  54233. // Create gaussian blur post-processes (down sampling blurs)
  54234. this._createBlurPostProcesses(scene, ratio / 4, 1);
  54235. // Create texture adder post-process
  54236. this._createTextureAdderPostProcess(scene, ratio);
  54237. // Create depth-of-field source post-process
  54238. 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);
  54239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54240. }
  54241. if (this._lensFlareEnabled) {
  54242. // Create lens flare post-process
  54243. this._createLensFlarePostProcess(scene, ratio);
  54244. // Create depth-of-field source post-process post lens-flare and disable it now
  54245. 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);
  54246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  54247. }
  54248. if (this._hdrEnabled) {
  54249. // Create luminance
  54250. this._createLuminancePostProcesses(scene, this._floatTextureType);
  54251. // Create HDR
  54252. this._createHdrPostProcess(scene, ratio);
  54253. // Create depth-of-field source post-process post hdr and disable it now
  54254. 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);
  54255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  54256. }
  54257. if (this._depthOfFieldEnabled) {
  54258. // Create gaussian blur used by depth-of-field
  54259. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  54260. // Create depth-of-field post-process
  54261. this._createDepthOfFieldPostProcess(scene, ratio);
  54262. }
  54263. if (this._motionBlurEnabled) {
  54264. // Create motion blur post-process
  54265. this._createMotionBlurPostProcess(scene, ratio);
  54266. }
  54267. if (this._cameras !== null) {
  54268. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54269. }
  54270. };
  54271. // Down Sample X4 Post-Processs
  54272. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54273. var _this = this;
  54274. var downSampleX4Offsets = new Array(32);
  54275. 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);
  54276. this.downSampleX4PostProcess.onApply = function (effect) {
  54277. var id = 0;
  54278. for (var i = -2; i < 2; i++) {
  54279. for (var j = -2; j < 2; j++) {
  54280. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54281. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54282. id += 2;
  54283. }
  54284. }
  54285. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54286. };
  54287. // Add to pipeline
  54288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54289. };
  54290. // Brightpass Post-Process
  54291. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54292. var _this = this;
  54293. var brightOffsets = new Array(8);
  54294. 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);
  54295. this.brightPassPostProcess.onApply = function (effect) {
  54296. var sU = (1.0 / _this.brightPassPostProcess.width);
  54297. var sV = (1.0 / _this.brightPassPostProcess.height);
  54298. brightOffsets[0] = -0.5 * sU;
  54299. brightOffsets[1] = 0.5 * sV;
  54300. brightOffsets[2] = 0.5 * sU;
  54301. brightOffsets[3] = 0.5 * sV;
  54302. brightOffsets[4] = -0.5 * sU;
  54303. brightOffsets[5] = -0.5 * sV;
  54304. brightOffsets[6] = 0.5 * sU;
  54305. brightOffsets[7] = -0.5 * sV;
  54306. effect.setArray2("dsOffsets", brightOffsets);
  54307. effect.setFloat("brightThreshold", _this.brightThreshold);
  54308. };
  54309. // Add to pipeline
  54310. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54311. };
  54312. // Create blur H&V post-processes
  54313. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  54314. var _this = this;
  54315. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  54316. var engine = scene.getEngine();
  54317. 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);
  54318. 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);
  54319. blurX.onActivateObservable.add(function () {
  54320. var dw = blurX.width / engine.getRenderingCanvas().width;
  54321. blurX.kernel = _this[blurWidthKey] * dw;
  54322. });
  54323. blurY.onActivateObservable.add(function () {
  54324. var dw = blurY.height / engine.getRenderingCanvas().height;
  54325. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  54326. });
  54327. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  54328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  54329. this.blurHPostProcesses.push(blurX);
  54330. this.blurVPostProcesses.push(blurY);
  54331. };
  54332. // Create texture adder post-process
  54333. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54334. var _this = this;
  54335. 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);
  54336. this.textureAdderPostProcess.onApply = function (effect) {
  54337. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  54338. effect.setTexture("lensSampler", _this.lensTexture);
  54339. effect.setFloat("exposure", _this.exposure);
  54340. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  54341. };
  54342. // Add to pipeline
  54343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54344. };
  54345. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  54346. var _this = this;
  54347. var geometryRenderer = scene.enableGeometryBufferRenderer();
  54348. geometryRenderer.enablePosition = true;
  54349. var geometry = geometryRenderer.getGBuffer();
  54350. // Base post-process
  54351. 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));
  54352. var depthValues = BABYLON.Vector2.Zero();
  54353. this.volumetricLightPostProcess.onApply = function (effect) {
  54354. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  54355. var generator = _this.sourceLight.getShadowGenerator();
  54356. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  54357. effect.setTexture("positionSampler", geometry.textures[2]);
  54358. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  54359. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  54360. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  54361. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  54362. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  54363. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  54364. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  54365. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  54366. effect.setVector2("depthValues", depthValues);
  54367. }
  54368. };
  54369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  54370. // Smooth
  54371. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  54372. // Merge
  54373. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  54374. this.volumetricLightMergePostProces.onApply = function (effect) {
  54375. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  54376. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  54377. };
  54378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  54379. };
  54380. // Create luminance
  54381. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  54382. var _this = this;
  54383. // Create luminance
  54384. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  54385. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  54386. var offsets = [];
  54387. this.luminancePostProcess.onApply = function (effect) {
  54388. var sU = (1.0 / _this.luminancePostProcess.width);
  54389. var sV = (1.0 / _this.luminancePostProcess.height);
  54390. offsets[0] = -0.5 * sU;
  54391. offsets[1] = 0.5 * sV;
  54392. offsets[2] = 0.5 * sU;
  54393. offsets[3] = 0.5 * sV;
  54394. offsets[4] = -0.5 * sU;
  54395. offsets[5] = -0.5 * sV;
  54396. offsets[6] = 0.5 * sU;
  54397. offsets[7] = -0.5 * sV;
  54398. effect.setArray2("lumOffsets", offsets);
  54399. };
  54400. // Add to pipeline
  54401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  54402. // Create down sample luminance
  54403. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  54404. var size = Math.pow(3, i);
  54405. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  54406. if (i === 0) {
  54407. defines += "#define FINAL_DOWN_SAMPLER";
  54408. }
  54409. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  54410. this.luminanceDownSamplePostProcesses.push(postProcess);
  54411. }
  54412. // Create callbacks and add effects
  54413. var lastLuminance = this.luminancePostProcess;
  54414. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  54415. var downSampleOffsets = new Array(18);
  54416. pp.onApply = function (effect) {
  54417. var id = 0;
  54418. for (var x = -1; x < 2; x++) {
  54419. for (var y = -1; y < 2; y++) {
  54420. downSampleOffsets[id] = x / lastLuminance.width;
  54421. downSampleOffsets[id + 1] = y / lastLuminance.height;
  54422. id += 2;
  54423. }
  54424. }
  54425. effect.setArray2("dsOffsets", downSampleOffsets);
  54426. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  54427. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54428. lastLuminance = _this.luminancePostProcess;
  54429. }
  54430. else {
  54431. lastLuminance = pp;
  54432. }
  54433. };
  54434. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54435. pp.onAfterRender = function (effect) {
  54436. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54437. 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);
  54438. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54439. };
  54440. }
  54441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  54442. });
  54443. };
  54444. // Create HDR post-process
  54445. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  54446. var _this = this;
  54447. 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);
  54448. var outputLiminance = 1;
  54449. var time = 0;
  54450. var lastTime = 0;
  54451. this.hdrPostProcess.onApply = function (effect) {
  54452. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  54453. time += scene.getEngine().getDeltaTime();
  54454. if (outputLiminance < 0) {
  54455. outputLiminance = _this._hdrCurrentLuminance;
  54456. }
  54457. else {
  54458. var dt = (lastTime - time) / 1000.0;
  54459. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  54460. outputLiminance += _this.hdrDecreaseRate * dt;
  54461. }
  54462. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  54463. outputLiminance -= _this.hdrIncreaseRate * dt;
  54464. }
  54465. else {
  54466. outputLiminance = _this._hdrCurrentLuminance;
  54467. }
  54468. }
  54469. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  54470. effect.setFloat("averageLuminance", outputLiminance);
  54471. lastTime = time;
  54472. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  54473. };
  54474. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  54475. };
  54476. // Create lens flare post-process
  54477. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54478. var _this = this;
  54479. 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);
  54480. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  54481. this._createBlurPostProcesses(scene, ratio / 4, 2);
  54482. 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);
  54483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  54484. var resolution = new BABYLON.Vector2(0, 0);
  54485. // Lens flare
  54486. this.lensFlarePostProcess.onApply = function (effect) {
  54487. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  54488. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54489. effect.setFloat("strength", _this.lensFlareStrength);
  54490. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54491. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54492. // Shift
  54493. resolution.x = _this.lensFlarePostProcess.width;
  54494. resolution.y = _this.lensFlarePostProcess.height;
  54495. effect.setVector2("resolution", resolution);
  54496. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54497. };
  54498. // Compose
  54499. 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);
  54500. 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);
  54501. this.lensFlareComposePostProcess.onApply = function (effect) {
  54502. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54503. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54504. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54505. // Lens start rotation matrix
  54506. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54507. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54508. 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));
  54509. camRot *= 4.0;
  54510. 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);
  54511. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54512. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54513. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  54514. };
  54515. };
  54516. // Create depth-of-field post-process
  54517. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54518. var _this = this;
  54519. 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);
  54520. this.depthOfFieldPostProcess.onApply = function (effect) {
  54521. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54522. effect.setTexture("depthSampler", _this._getDepthTexture());
  54523. effect.setFloat("distance", _this.depthOfFieldDistance);
  54524. };
  54525. // Add to pipeline
  54526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54527. };
  54528. // Create motion blur post-process
  54529. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  54530. var _this = this;
  54531. 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);
  54532. var motionScale = 0;
  54533. var prevViewProjection = BABYLON.Matrix.Identity();
  54534. var invViewProjection = BABYLON.Matrix.Identity();
  54535. var viewProjection = BABYLON.Matrix.Identity();
  54536. var screenSize = BABYLON.Vector2.Zero();
  54537. this.motionBlurPostProcess.onApply = function (effect) {
  54538. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  54539. viewProjection.invertToRef(invViewProjection);
  54540. effect.setMatrix("inverseViewProjection", invViewProjection);
  54541. effect.setMatrix("prevViewProjection", prevViewProjection);
  54542. prevViewProjection = viewProjection;
  54543. screenSize.x = _this.motionBlurPostProcess.width;
  54544. screenSize.y = _this.motionBlurPostProcess.height;
  54545. effect.setVector2("screenSize", screenSize);
  54546. motionScale = scene.getEngine().getFps() / 60.0;
  54547. effect.setFloat("motionScale", motionScale);
  54548. effect.setFloat("motionStrength", _this.motionStrength);
  54549. effect.setTexture("depthSampler", _this._getDepthTexture());
  54550. };
  54551. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  54552. };
  54553. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  54554. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  54555. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54556. }
  54557. return this._scene.enableDepthRenderer().getDepthMap();
  54558. };
  54559. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  54560. for (var i = 0; i < this._cameras.length; i++) {
  54561. var camera = this._cameras[i];
  54562. if (this.originalPostProcess) {
  54563. this.originalPostProcess.dispose(camera);
  54564. }
  54565. if (this.downSampleX4PostProcess) {
  54566. this.downSampleX4PostProcess.dispose(camera);
  54567. }
  54568. if (this.brightPassPostProcess) {
  54569. this.brightPassPostProcess.dispose(camera);
  54570. }
  54571. if (this.textureAdderPostProcess) {
  54572. this.textureAdderPostProcess.dispose(camera);
  54573. }
  54574. if (this.textureAdderFinalPostProcess) {
  54575. this.textureAdderFinalPostProcess.dispose(camera);
  54576. }
  54577. if (this.volumetricLightPostProcess) {
  54578. this.volumetricLightPostProcess.dispose(camera);
  54579. }
  54580. if (this.volumetricLightSmoothXPostProcess) {
  54581. this.volumetricLightSmoothXPostProcess.dispose(camera);
  54582. }
  54583. if (this.volumetricLightSmoothYPostProcess) {
  54584. this.volumetricLightSmoothYPostProcess.dispose(camera);
  54585. }
  54586. if (this.volumetricLightMergePostProces) {
  54587. this.volumetricLightMergePostProces.dispose(camera);
  54588. }
  54589. if (this.volumetricLightFinalPostProcess) {
  54590. this.volumetricLightFinalPostProcess.dispose(camera);
  54591. }
  54592. if (this.lensFlarePostProcess) {
  54593. this.lensFlarePostProcess.dispose(camera);
  54594. }
  54595. if (this.lensFlareComposePostProcess) {
  54596. this.lensFlareComposePostProcess.dispose(camera);
  54597. }
  54598. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  54599. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  54600. }
  54601. if (this.luminancePostProcess) {
  54602. this.luminancePostProcess.dispose(camera);
  54603. }
  54604. if (this.hdrPostProcess) {
  54605. this.hdrPostProcess.dispose(camera);
  54606. }
  54607. if (this.hdrFinalPostProcess) {
  54608. this.hdrFinalPostProcess.dispose(camera);
  54609. }
  54610. if (this.depthOfFieldPostProcess) {
  54611. this.depthOfFieldPostProcess.dispose(camera);
  54612. }
  54613. if (this.motionBlurPostProcess) {
  54614. this.motionBlurPostProcess.dispose(camera);
  54615. }
  54616. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  54617. this.blurHPostProcesses[j].dispose(camera);
  54618. }
  54619. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  54620. this.blurVPostProcesses[j].dispose(camera);
  54621. }
  54622. }
  54623. this.originalPostProcess = null;
  54624. this.downSampleX4PostProcess = null;
  54625. this.brightPassPostProcess = null;
  54626. this.textureAdderPostProcess = null;
  54627. this.textureAdderFinalPostProcess = null;
  54628. this.volumetricLightPostProcess = null;
  54629. this.volumetricLightSmoothXPostProcess = null;
  54630. this.volumetricLightSmoothYPostProcess = null;
  54631. this.volumetricLightMergePostProces = null;
  54632. this.volumetricLightFinalPostProcess = null;
  54633. this.lensFlarePostProcess = null;
  54634. this.lensFlareComposePostProcess = null;
  54635. this.luminancePostProcess = null;
  54636. this.hdrPostProcess = null;
  54637. this.hdrFinalPostProcess = null;
  54638. this.depthOfFieldPostProcess = null;
  54639. this.motionBlurPostProcess = null;
  54640. this.luminanceDownSamplePostProcesses = [];
  54641. this.blurHPostProcesses = [];
  54642. this.blurVPostProcesses = [];
  54643. };
  54644. // Dispose
  54645. StandardRenderingPipeline.prototype.dispose = function () {
  54646. this._disposePostProcesses();
  54647. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54648. _super.prototype.dispose.call(this);
  54649. };
  54650. // Serialize rendering pipeline
  54651. StandardRenderingPipeline.prototype.serialize = function () {
  54652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54653. serializationObject.customType = "StandardRenderingPipeline";
  54654. return serializationObject;
  54655. };
  54656. /**
  54657. * Static members
  54658. */
  54659. // Parse serialized pipeline
  54660. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54661. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  54662. };
  54663. // Luminance steps
  54664. StandardRenderingPipeline.LuminanceSteps = 6;
  54665. __decorate([
  54666. BABYLON.serialize()
  54667. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  54668. __decorate([
  54669. BABYLON.serialize()
  54670. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  54671. __decorate([
  54672. BABYLON.serialize()
  54673. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  54674. __decorate([
  54675. BABYLON.serialize()
  54676. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  54677. __decorate([
  54678. BABYLON.serializeAsTexture("lensTexture")
  54679. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  54680. __decorate([
  54681. BABYLON.serialize()
  54682. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  54683. __decorate([
  54684. BABYLON.serialize()
  54685. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  54686. __decorate([
  54687. BABYLON.serialize()
  54688. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  54689. __decorate([
  54690. BABYLON.serialize()
  54691. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  54692. __decorate([
  54693. BABYLON.serialize()
  54694. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  54695. __decorate([
  54696. BABYLON.serialize()
  54697. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  54698. __decorate([
  54699. BABYLON.serializeAsTexture("lensColorTexture")
  54700. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  54701. __decorate([
  54702. BABYLON.serialize()
  54703. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  54704. __decorate([
  54705. BABYLON.serialize()
  54706. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  54707. __decorate([
  54708. BABYLON.serialize()
  54709. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  54710. __decorate([
  54711. BABYLON.serialize()
  54712. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  54713. __decorate([
  54714. BABYLON.serializeAsTexture("lensStarTexture")
  54715. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  54716. __decorate([
  54717. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  54718. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  54719. __decorate([
  54720. BABYLON.serialize()
  54721. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  54722. __decorate([
  54723. BABYLON.serialize()
  54724. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  54725. __decorate([
  54726. BABYLON.serialize()
  54727. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  54728. __decorate([
  54729. BABYLON.serialize()
  54730. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  54731. __decorate([
  54732. BABYLON.serialize()
  54733. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  54734. __decorate([
  54735. BABYLON.serialize()
  54736. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  54737. __decorate([
  54738. BABYLON.serialize()
  54739. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  54740. __decorate([
  54741. BABYLON.serialize()
  54742. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  54743. __decorate([
  54744. BABYLON.serialize()
  54745. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  54746. __decorate([
  54747. BABYLON.serialize()
  54748. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  54749. __decorate([
  54750. BABYLON.serialize()
  54751. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  54752. return StandardRenderingPipeline;
  54753. }(BABYLON.PostProcessRenderPipeline));
  54754. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54755. })(BABYLON || (BABYLON = {}));
  54756. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54757. var BABYLON;
  54758. (function (BABYLON) {
  54759. var FxaaPostProcess = (function (_super) {
  54760. __extends(FxaaPostProcess, _super);
  54761. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54762. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54763. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  54764. _this.onApplyObservable.add(function (effect) {
  54765. var texelSize = _this.texelSize;
  54766. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  54767. });
  54768. return _this;
  54769. }
  54770. return FxaaPostProcess;
  54771. }(BABYLON.PostProcess));
  54772. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54773. })(BABYLON || (BABYLON = {}));
  54774. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  54775. var BABYLON;
  54776. (function (BABYLON) {
  54777. var DefaultRenderingPipeline = (function (_super) {
  54778. __extends(DefaultRenderingPipeline, _super);
  54779. /**
  54780. * @constructor
  54781. * @param {string} name - The rendering pipeline name
  54782. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54783. * @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)
  54784. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54785. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  54786. */
  54787. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  54788. if (automaticBuild === void 0) { automaticBuild = true; }
  54789. var _this = _super.call(this, scene.getEngine(), name) || this;
  54790. _this.PassPostProcessId = "PassPostProcessEffect";
  54791. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  54792. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  54793. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  54794. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  54795. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  54796. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  54797. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  54798. // IAnimatable
  54799. _this.animations = [];
  54800. // Values
  54801. _this._bloomEnabled = false;
  54802. _this._fxaaEnabled = false;
  54803. _this._imageProcessingEnabled = true;
  54804. _this._bloomScale = 0.6;
  54805. _this._buildAllowed = true;
  54806. /**
  54807. * Specifies the size of the bloom blur kernel, relative to the final output size
  54808. */
  54809. _this.bloomKernel = 64;
  54810. /**
  54811. * Specifies the weight of the bloom in the final rendering
  54812. */
  54813. _this._bloomWeight = 0.15;
  54814. _this._cameras = cameras || [];
  54815. _this._buildAllowed = automaticBuild;
  54816. // Initialize
  54817. _this._scene = scene;
  54818. var caps = _this._scene.getEngine().getCaps();
  54819. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  54820. // Misc
  54821. if (_this._hdr) {
  54822. if (caps.textureHalfFloatRender) {
  54823. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54824. }
  54825. else if (caps.textureFloatRender) {
  54826. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54827. }
  54828. }
  54829. else {
  54830. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54831. }
  54832. // Attach
  54833. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54834. _this._buildPipeline();
  54835. return _this;
  54836. }
  54837. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  54838. get: function () {
  54839. return this._bloomWeight;
  54840. },
  54841. set: function (value) {
  54842. if (this._bloomWeight === value) {
  54843. return;
  54844. }
  54845. this._bloomWeight = value;
  54846. if (this._hdr && this.copyBack) {
  54847. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  54848. }
  54849. },
  54850. enumerable: true,
  54851. configurable: true
  54852. });
  54853. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  54854. get: function () {
  54855. return this._bloomScale;
  54856. },
  54857. set: function (value) {
  54858. if (this._bloomScale === value) {
  54859. return;
  54860. }
  54861. this._bloomScale = value;
  54862. this._buildPipeline();
  54863. },
  54864. enumerable: true,
  54865. configurable: true
  54866. });
  54867. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  54868. get: function () {
  54869. return this._bloomEnabled;
  54870. },
  54871. set: function (enabled) {
  54872. if (this._bloomEnabled === enabled) {
  54873. return;
  54874. }
  54875. this._bloomEnabled = enabled;
  54876. this._buildPipeline();
  54877. },
  54878. enumerable: true,
  54879. configurable: true
  54880. });
  54881. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  54882. get: function () {
  54883. return this._fxaaEnabled;
  54884. },
  54885. set: function (enabled) {
  54886. if (this._fxaaEnabled === enabled) {
  54887. return;
  54888. }
  54889. this._fxaaEnabled = enabled;
  54890. this._buildPipeline();
  54891. },
  54892. enumerable: true,
  54893. configurable: true
  54894. });
  54895. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  54896. get: function () {
  54897. return this._imageProcessingEnabled;
  54898. },
  54899. set: function (enabled) {
  54900. if (this._imageProcessingEnabled === enabled) {
  54901. return;
  54902. }
  54903. this._imageProcessingEnabled = enabled;
  54904. this._buildPipeline();
  54905. },
  54906. enumerable: true,
  54907. configurable: true
  54908. });
  54909. /**
  54910. * Force the compilation of the entire pipeline.
  54911. */
  54912. DefaultRenderingPipeline.prototype.prepare = function () {
  54913. var previousState = this._buildAllowed;
  54914. this._buildAllowed = true;
  54915. this._buildPipeline();
  54916. this._buildAllowed = previousState;
  54917. };
  54918. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  54919. var _this = this;
  54920. if (!this._buildAllowed) {
  54921. return;
  54922. }
  54923. var engine = this._scene.getEngine();
  54924. this._disposePostProcesses();
  54925. this._reset();
  54926. if (this.bloomEnabled) {
  54927. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54928. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  54929. if (!this._hdr) {
  54930. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54931. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  54932. this.highlights.autoClear = false;
  54933. this.highlights.alwaysForcePOT = true;
  54934. }
  54935. 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);
  54936. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  54937. this.blurX.alwaysForcePOT = true;
  54938. this.blurX.autoClear = false;
  54939. this.blurX.onActivateObservable.add(function () {
  54940. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  54941. _this.blurX.kernel = _this.bloomKernel * dw;
  54942. });
  54943. 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);
  54944. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  54945. this.blurY.alwaysForcePOT = true;
  54946. this.blurY.autoClear = false;
  54947. this.blurY.onActivateObservable.add(function () {
  54948. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  54949. _this.blurY.kernel = _this.bloomKernel * dh;
  54950. });
  54951. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54952. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  54953. this.copyBack.alwaysForcePOT = true;
  54954. if (this._hdr) {
  54955. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  54956. var w = this.bloomWeight;
  54957. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  54958. }
  54959. else {
  54960. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  54961. }
  54962. this.copyBack.autoClear = false;
  54963. }
  54964. if (this._imageProcessingEnabled) {
  54965. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54966. if (this._hdr) {
  54967. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  54968. }
  54969. else {
  54970. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  54971. }
  54972. }
  54973. if (this.fxaaEnabled) {
  54974. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54975. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  54976. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54977. }
  54978. else {
  54979. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54980. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  54981. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54982. }
  54983. if (this.bloomEnabled) {
  54984. if (this._hdr) {
  54985. this.copyBack.shareOutputWith(this.blurX);
  54986. if (this.imageProcessing) {
  54987. this.imageProcessing.shareOutputWith(this.pass);
  54988. this.imageProcessing.autoClear = false;
  54989. }
  54990. else if (this.fxaa) {
  54991. this.fxaa.shareOutputWith(this.pass);
  54992. }
  54993. else {
  54994. this.finalMerge.shareOutputWith(this.pass);
  54995. }
  54996. }
  54997. else {
  54998. if (this.fxaa) {
  54999. this.fxaa.shareOutputWith(this.pass);
  55000. }
  55001. else {
  55002. this.finalMerge.shareOutputWith(this.pass);
  55003. }
  55004. }
  55005. }
  55006. if (this._cameras !== null) {
  55007. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  55008. }
  55009. };
  55010. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  55011. for (var i = 0; i < this._cameras.length; i++) {
  55012. var camera = this._cameras[i];
  55013. if (this.pass) {
  55014. this.pass.dispose(camera);
  55015. }
  55016. if (this.highlights) {
  55017. this.highlights.dispose(camera);
  55018. }
  55019. if (this.blurX) {
  55020. this.blurX.dispose(camera);
  55021. }
  55022. if (this.blurY) {
  55023. this.blurY.dispose(camera);
  55024. }
  55025. if (this.copyBack) {
  55026. this.copyBack.dispose(camera);
  55027. }
  55028. if (this.imageProcessing) {
  55029. this.imageProcessing.dispose(camera);
  55030. }
  55031. if (this.fxaa) {
  55032. this.fxaa.dispose(camera);
  55033. }
  55034. if (this.finalMerge) {
  55035. this.finalMerge.dispose(camera);
  55036. }
  55037. }
  55038. this.pass = null;
  55039. this.highlights = null;
  55040. this.blurX = null;
  55041. this.blurY = null;
  55042. this.copyBack = null;
  55043. this.imageProcessing = null;
  55044. this.fxaa = null;
  55045. this.finalMerge = null;
  55046. };
  55047. // Dispose
  55048. DefaultRenderingPipeline.prototype.dispose = function () {
  55049. this._disposePostProcesses();
  55050. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  55051. _super.prototype.dispose.call(this);
  55052. };
  55053. // Serialize rendering pipeline
  55054. DefaultRenderingPipeline.prototype.serialize = function () {
  55055. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55056. serializationObject.customType = "DefaultRenderingPipeline";
  55057. return serializationObject;
  55058. };
  55059. // Parse serialized pipeline
  55060. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55061. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  55062. };
  55063. __decorate([
  55064. BABYLON.serialize()
  55065. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  55066. __decorate([
  55067. BABYLON.serialize()
  55068. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  55069. __decorate([
  55070. BABYLON.serialize()
  55071. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  55072. __decorate([
  55073. BABYLON.serialize()
  55074. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  55075. __decorate([
  55076. BABYLON.serialize()
  55077. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  55078. __decorate([
  55079. BABYLON.serialize()
  55080. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  55081. __decorate([
  55082. BABYLON.serialize()
  55083. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  55084. __decorate([
  55085. BABYLON.serialize()
  55086. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  55087. return DefaultRenderingPipeline;
  55088. }(BABYLON.PostProcessRenderPipeline));
  55089. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  55090. })(BABYLON || (BABYLON = {}));
  55091. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  55092. var BABYLON;
  55093. (function (BABYLON) {
  55094. var GeometryBufferRenderer = (function () {
  55095. function GeometryBufferRenderer(scene, ratio) {
  55096. if (ratio === void 0) { ratio = 1; }
  55097. this._viewMatrix = BABYLON.Matrix.Zero();
  55098. this._projectionMatrix = BABYLON.Matrix.Zero();
  55099. this._transformMatrix = BABYLON.Matrix.Zero();
  55100. this._worldViewProjection = BABYLON.Matrix.Zero();
  55101. this._enablePosition = false;
  55102. this._scene = scene;
  55103. this._ratio = ratio;
  55104. // Render target
  55105. this._createRenderTargets();
  55106. }
  55107. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  55108. set: function (meshes) {
  55109. this._multiRenderTarget.renderList = meshes;
  55110. },
  55111. enumerable: true,
  55112. configurable: true
  55113. });
  55114. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  55115. get: function () {
  55116. return this._multiRenderTarget.isSupported;
  55117. },
  55118. enumerable: true,
  55119. configurable: true
  55120. });
  55121. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  55122. get: function () {
  55123. return this._enablePosition;
  55124. },
  55125. set: function (enable) {
  55126. this._enablePosition = enable;
  55127. this.dispose();
  55128. this._createRenderTargets();
  55129. },
  55130. enumerable: true,
  55131. configurable: true
  55132. });
  55133. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  55134. var material = subMesh.getMaterial();
  55135. if (material && material.disableDepthWrite) {
  55136. return false;
  55137. }
  55138. var defines = [];
  55139. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  55140. var mesh = subMesh.getMesh();
  55141. var scene = mesh.getScene();
  55142. // Alpha test
  55143. if (material && material.needAlphaTesting()) {
  55144. defines.push("#define ALPHATEST");
  55145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55146. attribs.push(BABYLON.VertexBuffer.UVKind);
  55147. defines.push("#define UV1");
  55148. }
  55149. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55150. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55151. defines.push("#define UV2");
  55152. }
  55153. }
  55154. // Buffers
  55155. if (this._enablePosition) {
  55156. defines.push("#define POSITION");
  55157. }
  55158. // Bones
  55159. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55160. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55161. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55162. if (mesh.numBoneInfluencers > 4) {
  55163. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55164. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55165. }
  55166. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55167. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55168. }
  55169. else {
  55170. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55171. }
  55172. // Instances
  55173. if (useInstances) {
  55174. defines.push("#define INSTANCES");
  55175. attribs.push("world0");
  55176. attribs.push("world1");
  55177. attribs.push("world2");
  55178. attribs.push("world3");
  55179. }
  55180. // Get correct effect
  55181. var join = defines.join("\n");
  55182. if (this._cachedDefines !== join) {
  55183. this._cachedDefines = join;
  55184. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  55185. }
  55186. return this._effect.isReady();
  55187. };
  55188. GeometryBufferRenderer.prototype.getGBuffer = function () {
  55189. return this._multiRenderTarget;
  55190. };
  55191. // Methods
  55192. GeometryBufferRenderer.prototype.dispose = function () {
  55193. this.getGBuffer().dispose();
  55194. };
  55195. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  55196. var _this = this;
  55197. var engine = this._scene.getEngine();
  55198. var count = this._enablePosition ? 3 : 2;
  55199. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  55200. if (!this.isSupported) {
  55201. return null;
  55202. }
  55203. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55204. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55205. this._multiRenderTarget.refreshRate = 1;
  55206. this._multiRenderTarget.renderParticles = false;
  55207. this._multiRenderTarget.renderList = null;
  55208. // set default depth value to 1.0 (far away)
  55209. this._multiRenderTarget.onClearObservable.add(function (engine) {
  55210. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  55211. });
  55212. // Custom render function
  55213. var renderSubMesh = function (subMesh) {
  55214. var mesh = subMesh.getRenderingMesh();
  55215. var scene = _this._scene;
  55216. var engine = scene.getEngine();
  55217. // Culling
  55218. engine.setState(subMesh.getMaterial().backFaceCulling);
  55219. // Managing instances
  55220. var batch = mesh._getInstancesRenderList(subMesh._id);
  55221. if (batch.mustReturn) {
  55222. return;
  55223. }
  55224. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55225. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55226. engine.enableEffect(_this._effect);
  55227. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55228. var material = subMesh.getMaterial();
  55229. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55230. _this._effect.setMatrix("view", scene.getViewMatrix());
  55231. // Alpha test
  55232. if (material && material.needAlphaTesting()) {
  55233. var alphaTexture = material.getAlphaTestTexture();
  55234. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55235. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55236. }
  55237. // Bones
  55238. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55239. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55240. }
  55241. // Draw
  55242. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55243. }
  55244. };
  55245. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55246. var index;
  55247. if (depthOnlySubMeshes.length) {
  55248. engine.setColorWrite(false);
  55249. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55250. renderSubMesh(depthOnlySubMeshes.data[index]);
  55251. }
  55252. engine.setColorWrite(true);
  55253. }
  55254. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55255. renderSubMesh(opaqueSubMeshes.data[index]);
  55256. }
  55257. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55258. renderSubMesh(alphaTestSubMeshes.data[index]);
  55259. }
  55260. };
  55261. };
  55262. return GeometryBufferRenderer;
  55263. }());
  55264. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  55265. })(BABYLON || (BABYLON = {}));
  55266. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  55267. var BABYLON;
  55268. (function (BABYLON) {
  55269. var RefractionPostProcess = (function (_super) {
  55270. __extends(RefractionPostProcess, _super);
  55271. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  55272. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  55273. _this.color = color;
  55274. _this.depth = depth;
  55275. _this.colorLevel = colorLevel;
  55276. _this.onActivateObservable.add(function (cam) {
  55277. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  55278. });
  55279. _this.onApplyObservable.add(function (effect) {
  55280. effect.setColor3("baseColor", _this.color);
  55281. effect.setFloat("depth", _this.depth);
  55282. effect.setFloat("colorLevel", _this.colorLevel);
  55283. effect.setTexture("refractionSampler", _this._refRexture);
  55284. });
  55285. return _this;
  55286. }
  55287. // Methods
  55288. RefractionPostProcess.prototype.dispose = function (camera) {
  55289. if (this._refRexture) {
  55290. this._refRexture.dispose();
  55291. }
  55292. _super.prototype.dispose.call(this, camera);
  55293. };
  55294. return RefractionPostProcess;
  55295. }(BABYLON.PostProcess));
  55296. BABYLON.RefractionPostProcess = RefractionPostProcess;
  55297. })(BABYLON || (BABYLON = {}));
  55298. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  55299. var BABYLON;
  55300. (function (BABYLON) {
  55301. var BlackAndWhitePostProcess = (function (_super) {
  55302. __extends(BlackAndWhitePostProcess, _super);
  55303. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  55304. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  55305. _this.degree = 1;
  55306. _this.onApplyObservable.add(function (effect) {
  55307. effect.setFloat("degree", _this.degree);
  55308. });
  55309. return _this;
  55310. }
  55311. return BlackAndWhitePostProcess;
  55312. }(BABYLON.PostProcess));
  55313. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  55314. })(BABYLON || (BABYLON = {}));
  55315. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  55316. var BABYLON;
  55317. (function (BABYLON) {
  55318. var ConvolutionPostProcess = (function (_super) {
  55319. __extends(ConvolutionPostProcess, _super);
  55320. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  55321. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  55322. _this.kernel = kernel;
  55323. _this.onApply = function (effect) {
  55324. effect.setFloat2("screenSize", _this.width, _this.height);
  55325. effect.setArray("kernel", _this.kernel);
  55326. };
  55327. return _this;
  55328. }
  55329. // Statics
  55330. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  55331. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  55332. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  55333. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  55334. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  55335. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  55336. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  55337. return ConvolutionPostProcess;
  55338. }(BABYLON.PostProcess));
  55339. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  55340. })(BABYLON || (BABYLON = {}));
  55341. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  55342. var BABYLON;
  55343. (function (BABYLON) {
  55344. var FilterPostProcess = (function (_super) {
  55345. __extends(FilterPostProcess, _super);
  55346. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  55347. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  55348. _this.kernelMatrix = kernelMatrix;
  55349. _this.onApply = function (effect) {
  55350. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  55351. };
  55352. return _this;
  55353. }
  55354. return FilterPostProcess;
  55355. }(BABYLON.PostProcess));
  55356. BABYLON.FilterPostProcess = FilterPostProcess;
  55357. })(BABYLON || (BABYLON = {}));
  55358. //# sourceMappingURL=babylon.filterPostProcess.js.map
  55359. var BABYLON;
  55360. (function (BABYLON) {
  55361. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55362. var VolumetricLightScatteringPostProcess = (function (_super) {
  55363. __extends(VolumetricLightScatteringPostProcess, _super);
  55364. /**
  55365. * @constructor
  55366. * @param {string} name - The post-process name
  55367. * @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)
  55368. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55369. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55370. * @param {number} samples - The post-process quality, default 100
  55371. * @param {number} samplingMode - The post-process filtering mode
  55372. * @param {BABYLON.Engine} engine - The babylon engine
  55373. * @param {boolean} reusable - If the post-process is reusable
  55374. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55375. */
  55376. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55377. if (samples === void 0) { samples = 100; }
  55378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55379. 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;
  55380. _this._screenCoordinates = BABYLON.Vector2.Zero();
  55381. /**
  55382. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55383. * @type {Vector3}
  55384. */
  55385. _this.customMeshPosition = BABYLON.Vector3.Zero();
  55386. /**
  55387. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55388. * @type {boolean}
  55389. */
  55390. _this.useCustomMeshPosition = false;
  55391. /**
  55392. * If the post-process should inverse the light scattering direction
  55393. * @type {boolean}
  55394. */
  55395. _this.invert = true;
  55396. /**
  55397. * Array containing the excluded meshes not rendered in the internal pass
  55398. */
  55399. _this.excludedMeshes = new Array();
  55400. /**
  55401. * Controls the overall intensity of the post-process
  55402. * @type {number}
  55403. */
  55404. _this.exposure = 0.3;
  55405. /**
  55406. * Dissipates each sample's contribution in range [0, 1]
  55407. * @type {number}
  55408. */
  55409. _this.decay = 0.96815;
  55410. /**
  55411. * Controls the overall intensity of each sample
  55412. * @type {number}
  55413. */
  55414. _this.weight = 0.58767;
  55415. /**
  55416. * Controls the density of each sample
  55417. * @type {number}
  55418. */
  55419. _this.density = 0.926;
  55420. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55421. var engine = scene.getEngine();
  55422. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55423. // Configure mesh
  55424. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55425. // Configure
  55426. _this._createPass(scene, ratio.passRatio || ratio);
  55427. _this.onActivate = function (camera) {
  55428. if (!_this.isSupported) {
  55429. _this.dispose(camera);
  55430. }
  55431. _this.onActivate = null;
  55432. };
  55433. _this.onApplyObservable.add(function (effect) {
  55434. _this._updateMeshScreenCoordinates(scene);
  55435. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55436. effect.setFloat("exposure", _this.exposure);
  55437. effect.setFloat("decay", _this.decay);
  55438. effect.setFloat("weight", _this.weight);
  55439. effect.setFloat("density", _this.density);
  55440. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55441. });
  55442. return _this;
  55443. }
  55444. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55445. get: function () {
  55446. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55447. return false;
  55448. },
  55449. set: function (useDiffuseColor) {
  55450. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55451. },
  55452. enumerable: true,
  55453. configurable: true
  55454. });
  55455. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  55456. return "VolumetricLightScatteringPostProcess";
  55457. };
  55458. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55459. var mesh = subMesh.getMesh();
  55460. // Render this.mesh as default
  55461. if (mesh === this.mesh) {
  55462. return mesh.material.isReady(mesh);
  55463. }
  55464. var defines = [];
  55465. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55466. var material = subMesh.getMaterial();
  55467. var needUV = false;
  55468. // Alpha test
  55469. if (material) {
  55470. if (material.needAlphaTesting()) {
  55471. defines.push("#define ALPHATEST");
  55472. }
  55473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55474. attribs.push(BABYLON.VertexBuffer.UVKind);
  55475. defines.push("#define UV1");
  55476. }
  55477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55478. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55479. defines.push("#define UV2");
  55480. }
  55481. }
  55482. // Bones
  55483. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55484. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55485. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55486. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55487. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55488. }
  55489. else {
  55490. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55491. }
  55492. // Instances
  55493. if (useInstances) {
  55494. defines.push("#define INSTANCES");
  55495. attribs.push("world0");
  55496. attribs.push("world1");
  55497. attribs.push("world2");
  55498. attribs.push("world3");
  55499. }
  55500. // Get correct effect
  55501. var join = defines.join("\n");
  55502. if (this._cachedDefines !== join) {
  55503. this._cachedDefines = join;
  55504. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55505. }
  55506. return this._volumetricLightScatteringPass.isReady();
  55507. };
  55508. /**
  55509. * Sets the new light position for light scattering effect
  55510. * @param {BABYLON.Vector3} The new custom light position
  55511. */
  55512. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55513. this.customMeshPosition = position;
  55514. };
  55515. /**
  55516. * Returns the light position for light scattering effect
  55517. * @return {BABYLON.Vector3} The custom light position
  55518. */
  55519. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55520. return this.customMeshPosition;
  55521. };
  55522. /**
  55523. * Disposes the internal assets and detaches the post-process from the camera
  55524. */
  55525. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55526. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55527. if (rttIndex !== -1) {
  55528. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55529. }
  55530. this._volumetricLightScatteringRTT.dispose();
  55531. _super.prototype.dispose.call(this, camera);
  55532. };
  55533. /**
  55534. * Returns the render target texture used by the post-process
  55535. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55536. */
  55537. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55538. return this._volumetricLightScatteringRTT;
  55539. };
  55540. // Private methods
  55541. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55542. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55543. return true;
  55544. }
  55545. return false;
  55546. };
  55547. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55548. var _this = this;
  55549. var engine = scene.getEngine();
  55550. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55551. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55552. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55553. this._volumetricLightScatteringRTT.renderList = null;
  55554. this._volumetricLightScatteringRTT.renderParticles = false;
  55555. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55556. // Custom render function for submeshes
  55557. var renderSubMesh = function (subMesh) {
  55558. var mesh = subMesh.getRenderingMesh();
  55559. if (_this._meshExcluded(mesh)) {
  55560. return;
  55561. }
  55562. var scene = mesh.getScene();
  55563. var engine = scene.getEngine();
  55564. // Culling
  55565. engine.setState(subMesh.getMaterial().backFaceCulling);
  55566. // Managing instances
  55567. var batch = mesh._getInstancesRenderList(subMesh._id);
  55568. if (batch.mustReturn) {
  55569. return;
  55570. }
  55571. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55572. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55573. var effect = _this._volumetricLightScatteringPass;
  55574. if (mesh === _this.mesh) {
  55575. if (subMesh.effect) {
  55576. effect = subMesh.effect;
  55577. }
  55578. else {
  55579. effect = subMesh.getMaterial().getEffect();
  55580. }
  55581. }
  55582. engine.enableEffect(effect);
  55583. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55584. if (mesh === _this.mesh) {
  55585. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55586. }
  55587. else {
  55588. var material = subMesh.getMaterial();
  55589. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55590. // Alpha test
  55591. if (material && material.needAlphaTesting()) {
  55592. var alphaTexture = material.getAlphaTestTexture();
  55593. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55594. if (alphaTexture) {
  55595. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55596. }
  55597. }
  55598. // Bones
  55599. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55600. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55601. }
  55602. }
  55603. // Draw
  55604. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55605. }
  55606. };
  55607. // Render target texture callbacks
  55608. var savedSceneClearColor;
  55609. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55610. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55611. savedSceneClearColor = scene.clearColor;
  55612. scene.clearColor = sceneClearColor;
  55613. });
  55614. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55615. scene.clearColor = savedSceneClearColor;
  55616. });
  55617. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55618. var engine = scene.getEngine();
  55619. var index;
  55620. if (depthOnlySubMeshes.length) {
  55621. engine.setColorWrite(false);
  55622. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55623. renderSubMesh(depthOnlySubMeshes.data[index]);
  55624. }
  55625. engine.setColorWrite(true);
  55626. }
  55627. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55628. renderSubMesh(opaqueSubMeshes.data[index]);
  55629. }
  55630. engine.setAlphaTesting(true);
  55631. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55632. renderSubMesh(alphaTestSubMeshes.data[index]);
  55633. }
  55634. engine.setAlphaTesting(false);
  55635. if (transparentSubMeshes.length) {
  55636. // Sort sub meshes
  55637. for (index = 0; index < transparentSubMeshes.length; index++) {
  55638. var submesh = transparentSubMeshes.data[index];
  55639. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55640. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55641. }
  55642. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55643. sortedArray.sort(function (a, b) {
  55644. // Alpha index first
  55645. if (a._alphaIndex > b._alphaIndex) {
  55646. return 1;
  55647. }
  55648. if (a._alphaIndex < b._alphaIndex) {
  55649. return -1;
  55650. }
  55651. // Then distance to camera
  55652. if (a._distanceToCamera < b._distanceToCamera) {
  55653. return 1;
  55654. }
  55655. if (a._distanceToCamera > b._distanceToCamera) {
  55656. return -1;
  55657. }
  55658. return 0;
  55659. });
  55660. // Render sub meshes
  55661. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55662. for (index = 0; index < sortedArray.length; index++) {
  55663. renderSubMesh(sortedArray[index]);
  55664. }
  55665. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55666. }
  55667. };
  55668. };
  55669. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55670. var transform = scene.getTransformMatrix();
  55671. var meshPosition;
  55672. if (this.useCustomMeshPosition) {
  55673. meshPosition = this.customMeshPosition;
  55674. }
  55675. else if (this.attachedNode) {
  55676. meshPosition = this.attachedNode.position;
  55677. }
  55678. else {
  55679. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55680. }
  55681. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55682. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55683. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55684. if (this.invert)
  55685. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55686. };
  55687. // Static methods
  55688. /**
  55689. * Creates a default mesh for the Volumeric Light Scattering post-process
  55690. * @param {string} The mesh name
  55691. * @param {BABYLON.Scene} The scene where to create the mesh
  55692. * @return {BABYLON.Mesh} the default mesh
  55693. */
  55694. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55695. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55696. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55697. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55698. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55699. mesh.material = material;
  55700. return mesh;
  55701. };
  55702. __decorate([
  55703. BABYLON.serializeAsVector3()
  55704. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55705. __decorate([
  55706. BABYLON.serialize()
  55707. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55708. __decorate([
  55709. BABYLON.serialize()
  55710. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55711. __decorate([
  55712. BABYLON.serializeAsMeshReference()
  55713. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55714. __decorate([
  55715. BABYLON.serialize()
  55716. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55717. __decorate([
  55718. BABYLON.serialize()
  55719. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55720. __decorate([
  55721. BABYLON.serialize()
  55722. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55723. __decorate([
  55724. BABYLON.serialize()
  55725. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55726. __decorate([
  55727. BABYLON.serialize()
  55728. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55729. return VolumetricLightScatteringPostProcess;
  55730. }(BABYLON.PostProcess));
  55731. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55732. })(BABYLON || (BABYLON = {}));
  55733. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  55734. //
  55735. // This post-process allows the modification of rendered colors by using
  55736. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55737. //
  55738. // The object needs to be provided an url to a texture containing the color
  55739. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55740. // Use an image editing software to tweak the LUT to match your needs.
  55741. //
  55742. // For an example of a color LUT, see here:
  55743. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55744. // For explanations on color grading, see here:
  55745. // http://udn.epicgames.com/Three/ColorGrading.html
  55746. //
  55747. var BABYLON;
  55748. (function (BABYLON) {
  55749. var ColorCorrectionPostProcess = (function (_super) {
  55750. __extends(ColorCorrectionPostProcess, _super);
  55751. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55752. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  55753. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55754. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  55755. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55756. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55757. _this.onApply = function (effect) {
  55758. effect.setTexture("colorTable", _this._colorTableTexture);
  55759. };
  55760. return _this;
  55761. }
  55762. return ColorCorrectionPostProcess;
  55763. }(BABYLON.PostProcess));
  55764. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55765. })(BABYLON || (BABYLON = {}));
  55766. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  55767. var BABYLON;
  55768. (function (BABYLON) {
  55769. var TonemappingOperator;
  55770. (function (TonemappingOperator) {
  55771. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55772. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55773. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55774. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55775. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55776. ;
  55777. var TonemapPostProcess = (function (_super) {
  55778. __extends(TonemapPostProcess, _super);
  55779. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55781. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55782. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  55783. _this._operator = _operator;
  55784. _this.exposureAdjustment = exposureAdjustment;
  55785. var defines = "#define ";
  55786. if (_this._operator === TonemappingOperator.Hable)
  55787. defines += "HABLE_TONEMAPPING";
  55788. else if (_this._operator === TonemappingOperator.Reinhard)
  55789. defines += "REINHARD_TONEMAPPING";
  55790. else if (_this._operator === TonemappingOperator.HejiDawson)
  55791. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55792. else if (_this._operator === TonemappingOperator.Photographic)
  55793. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55794. //sadly a second call to create the effect.
  55795. _this.updateEffect(defines);
  55796. _this.onApply = function (effect) {
  55797. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55798. };
  55799. return _this;
  55800. }
  55801. return TonemapPostProcess;
  55802. }(BABYLON.PostProcess));
  55803. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55804. })(BABYLON || (BABYLON = {}));
  55805. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  55806. var BABYLON;
  55807. (function (BABYLON) {
  55808. var DisplayPassPostProcess = (function (_super) {
  55809. __extends(DisplayPassPostProcess, _super);
  55810. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  55811. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  55812. }
  55813. return DisplayPassPostProcess;
  55814. }(BABYLON.PostProcess));
  55815. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  55816. })(BABYLON || (BABYLON = {}));
  55817. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  55818. var BABYLON;
  55819. (function (BABYLON) {
  55820. var HighlightsPostProcess = (function (_super) {
  55821. __extends(HighlightsPostProcess, _super);
  55822. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55823. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55824. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  55825. }
  55826. return HighlightsPostProcess;
  55827. }(BABYLON.PostProcess));
  55828. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  55829. })(BABYLON || (BABYLON = {}));
  55830. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  55831. var BABYLON;
  55832. (function (BABYLON) {
  55833. var ImageProcessingPostProcess = (function (_super) {
  55834. __extends(ImageProcessingPostProcess, _super);
  55835. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55836. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55837. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  55838. _this._fromLinearSpace = true;
  55839. /**
  55840. * Defines cache preventing GC.
  55841. */
  55842. _this._defines = {
  55843. IMAGEPROCESSING: false,
  55844. VIGNETTE: false,
  55845. VIGNETTEBLENDMODEMULTIPLY: false,
  55846. VIGNETTEBLENDMODEOPAQUE: false,
  55847. TONEMAPPING: false,
  55848. CONTRAST: false,
  55849. COLORCURVES: false,
  55850. COLORGRADING: false,
  55851. FROMLINEARSPACE: false,
  55852. SAMPLER3DGREENDEPTH: false,
  55853. SAMPLER3DBGRMAP: false,
  55854. IMAGEPROCESSINGPOSTPROCESS: false,
  55855. EXPOSURE: false,
  55856. };
  55857. // Setup the default processing configuration to the scene.
  55858. _this._attachImageProcessingConfiguration(null, true);
  55859. _this.imageProcessingConfiguration.applyByPostProcess = true;
  55860. _this.onApply = function (effect) {
  55861. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  55862. };
  55863. return _this;
  55864. }
  55865. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  55866. /**
  55867. * Gets the image processing configuration used either in this material.
  55868. */
  55869. get: function () {
  55870. return this._imageProcessingConfiguration;
  55871. },
  55872. /**
  55873. * Sets the Default image processing configuration used either in the this material.
  55874. *
  55875. * If sets to null, the scene one is in use.
  55876. */
  55877. set: function (value) {
  55878. this._attachImageProcessingConfiguration(value);
  55879. },
  55880. enumerable: true,
  55881. configurable: true
  55882. });
  55883. /**
  55884. * Attaches a new image processing configuration to the PBR Material.
  55885. * @param configuration
  55886. */
  55887. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  55888. var _this = this;
  55889. if (doNotBuild === void 0) { doNotBuild = false; }
  55890. if (configuration === this._imageProcessingConfiguration) {
  55891. return;
  55892. }
  55893. // Detaches observer.
  55894. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55895. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55896. }
  55897. // Pick the scene configuration if needed.
  55898. if (!configuration) {
  55899. var camera = this.getCamera();
  55900. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  55901. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  55902. }
  55903. else {
  55904. this._imageProcessingConfiguration = configuration;
  55905. }
  55906. // Attaches observer.
  55907. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  55908. _this._updateParameters();
  55909. });
  55910. // Ensure the effect will be rebuilt.
  55911. if (!doNotBuild) {
  55912. this._updateParameters();
  55913. }
  55914. };
  55915. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  55916. /**
  55917. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  55918. */
  55919. get: function () {
  55920. return this.imageProcessingConfiguration.colorCurves;
  55921. },
  55922. /**
  55923. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  55924. */
  55925. set: function (value) {
  55926. this.imageProcessingConfiguration.colorCurves = value;
  55927. },
  55928. enumerable: true,
  55929. configurable: true
  55930. });
  55931. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  55932. /**
  55933. * Gets wether the color curves effect is enabled.
  55934. */
  55935. get: function () {
  55936. return this.imageProcessingConfiguration.colorCurvesEnabled;
  55937. },
  55938. /**
  55939. * Sets wether the color curves effect is enabled.
  55940. */
  55941. set: function (value) {
  55942. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  55943. },
  55944. enumerable: true,
  55945. configurable: true
  55946. });
  55947. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  55948. /**
  55949. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55950. */
  55951. get: function () {
  55952. return this.imageProcessingConfiguration.colorGradingTexture;
  55953. },
  55954. /**
  55955. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55956. */
  55957. set: function (value) {
  55958. this.imageProcessingConfiguration.colorGradingTexture = value;
  55959. },
  55960. enumerable: true,
  55961. configurable: true
  55962. });
  55963. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  55964. /**
  55965. * Gets wether the color grading effect is enabled.
  55966. */
  55967. get: function () {
  55968. return this.imageProcessingConfiguration.colorGradingEnabled;
  55969. },
  55970. /**
  55971. * Gets wether the color grading effect is enabled.
  55972. */
  55973. set: function (value) {
  55974. this.imageProcessingConfiguration.colorGradingEnabled = value;
  55975. },
  55976. enumerable: true,
  55977. configurable: true
  55978. });
  55979. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  55980. /**
  55981. * Gets exposure used in the effect.
  55982. */
  55983. get: function () {
  55984. return this.imageProcessingConfiguration.exposure;
  55985. },
  55986. /**
  55987. * Sets exposure used in the effect.
  55988. */
  55989. set: function (value) {
  55990. this.imageProcessingConfiguration.exposure = value;
  55991. },
  55992. enumerable: true,
  55993. configurable: true
  55994. });
  55995. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  55996. /**
  55997. * Gets wether tonemapping is enabled or not.
  55998. */
  55999. get: function () {
  56000. return this._imageProcessingConfiguration.toneMappingEnabled;
  56001. },
  56002. /**
  56003. * Sets wether tonemapping is enabled or not
  56004. */
  56005. set: function (value) {
  56006. this._imageProcessingConfiguration.toneMappingEnabled = value;
  56007. },
  56008. enumerable: true,
  56009. configurable: true
  56010. });
  56011. ;
  56012. ;
  56013. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  56014. /**
  56015. * Gets contrast used in the effect.
  56016. */
  56017. get: function () {
  56018. return this.imageProcessingConfiguration.contrast;
  56019. },
  56020. /**
  56021. * Sets contrast used in the effect.
  56022. */
  56023. set: function (value) {
  56024. this.imageProcessingConfiguration.contrast = value;
  56025. },
  56026. enumerable: true,
  56027. configurable: true
  56028. });
  56029. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  56030. /**
  56031. * Gets Vignette stretch size.
  56032. */
  56033. get: function () {
  56034. return this.imageProcessingConfiguration.vignetteStretch;
  56035. },
  56036. /**
  56037. * Sets Vignette stretch size.
  56038. */
  56039. set: function (value) {
  56040. this.imageProcessingConfiguration.vignetteStretch = value;
  56041. },
  56042. enumerable: true,
  56043. configurable: true
  56044. });
  56045. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  56046. /**
  56047. * Gets Vignette centre X Offset.
  56048. */
  56049. get: function () {
  56050. return this.imageProcessingConfiguration.vignetteCentreX;
  56051. },
  56052. /**
  56053. * Sets Vignette centre X Offset.
  56054. */
  56055. set: function (value) {
  56056. this.imageProcessingConfiguration.vignetteCentreX = value;
  56057. },
  56058. enumerable: true,
  56059. configurable: true
  56060. });
  56061. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  56062. /**
  56063. * Gets Vignette centre Y Offset.
  56064. */
  56065. get: function () {
  56066. return this.imageProcessingConfiguration.vignetteCentreY;
  56067. },
  56068. /**
  56069. * Sets Vignette centre Y Offset.
  56070. */
  56071. set: function (value) {
  56072. this.imageProcessingConfiguration.vignetteCentreY = value;
  56073. },
  56074. enumerable: true,
  56075. configurable: true
  56076. });
  56077. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  56078. /**
  56079. * Gets Vignette weight or intensity of the vignette effect.
  56080. */
  56081. get: function () {
  56082. return this.imageProcessingConfiguration.vignetteWeight;
  56083. },
  56084. /**
  56085. * Sets Vignette weight or intensity of the vignette effect.
  56086. */
  56087. set: function (value) {
  56088. this.imageProcessingConfiguration.vignetteWeight = value;
  56089. },
  56090. enumerable: true,
  56091. configurable: true
  56092. });
  56093. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  56094. /**
  56095. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56096. * if vignetteEnabled is set to true.
  56097. */
  56098. get: function () {
  56099. return this.imageProcessingConfiguration.vignetteColor;
  56100. },
  56101. /**
  56102. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56103. * if vignetteEnabled is set to true.
  56104. */
  56105. set: function (value) {
  56106. this.imageProcessingConfiguration.vignetteColor = value;
  56107. },
  56108. enumerable: true,
  56109. configurable: true
  56110. });
  56111. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  56112. /**
  56113. * Gets Camera field of view used by the Vignette effect.
  56114. */
  56115. get: function () {
  56116. return this.imageProcessingConfiguration.vignetteCameraFov;
  56117. },
  56118. /**
  56119. * Sets Camera field of view used by the Vignette effect.
  56120. */
  56121. set: function (value) {
  56122. this.imageProcessingConfiguration.vignetteCameraFov = value;
  56123. },
  56124. enumerable: true,
  56125. configurable: true
  56126. });
  56127. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  56128. /**
  56129. * Gets the vignette blend mode allowing different kind of effect.
  56130. */
  56131. get: function () {
  56132. return this.imageProcessingConfiguration.vignetteBlendMode;
  56133. },
  56134. /**
  56135. * Sets the vignette blend mode allowing different kind of effect.
  56136. */
  56137. set: function (value) {
  56138. this.imageProcessingConfiguration.vignetteBlendMode = value;
  56139. },
  56140. enumerable: true,
  56141. configurable: true
  56142. });
  56143. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  56144. /**
  56145. * Gets wether the vignette effect is enabled.
  56146. */
  56147. get: function () {
  56148. return this.imageProcessingConfiguration.vignetteEnabled;
  56149. },
  56150. /**
  56151. * Sets wether the vignette effect is enabled.
  56152. */
  56153. set: function (value) {
  56154. this.imageProcessingConfiguration.vignetteEnabled = value;
  56155. },
  56156. enumerable: true,
  56157. configurable: true
  56158. });
  56159. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  56160. /**
  56161. * Gets wether the input of the processing is in Gamma or Linear Space.
  56162. */
  56163. get: function () {
  56164. return this._fromLinearSpace;
  56165. },
  56166. /**
  56167. * Sets wether the input of the processing is in Gamma or Linear Space.
  56168. */
  56169. set: function (value) {
  56170. if (this._fromLinearSpace === value) {
  56171. return;
  56172. }
  56173. this._fromLinearSpace = value;
  56174. this._updateParameters();
  56175. },
  56176. enumerable: true,
  56177. configurable: true
  56178. });
  56179. ImageProcessingPostProcess.prototype.getClassName = function () {
  56180. return "ImageProcessingPostProcess";
  56181. };
  56182. ImageProcessingPostProcess.prototype._updateParameters = function () {
  56183. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  56184. this.imageProcessingConfiguration.prepareDefines(this._defines);
  56185. var defines = "";
  56186. for (var define in this._defines) {
  56187. if (this._defines[define]) {
  56188. defines += "#define " + define + ";\r\n";
  56189. }
  56190. }
  56191. var samplers = ["textureSampler"];
  56192. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  56193. var uniforms = ["scale"];
  56194. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  56195. this.updateEffect(defines, uniforms, samplers);
  56196. };
  56197. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  56198. _super.prototype.dispose.call(this, camera);
  56199. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56200. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56201. }
  56202. this.imageProcessingConfiguration.applyByPostProcess = false;
  56203. };
  56204. __decorate([
  56205. BABYLON.serialize()
  56206. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  56207. return ImageProcessingPostProcess;
  56208. }(BABYLON.PostProcess));
  56209. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  56210. })(BABYLON || (BABYLON = {}));
  56211. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  56212. var BABYLON;
  56213. (function (BABYLON) {
  56214. var BlurPostProcess = (function (_super) {
  56215. __extends(BlurPostProcess, _super);
  56216. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  56217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56218. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56219. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  56220. _this.direction = direction;
  56221. _this._packedFloat = false;
  56222. _this.onApplyObservable.add(function (effect) {
  56223. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  56224. });
  56225. _this.kernel = kernel;
  56226. return _this;
  56227. }
  56228. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  56229. /**
  56230. * Gets the length in pixels of the blur sample region
  56231. */
  56232. get: function () {
  56233. return this._idealKernel;
  56234. },
  56235. /**
  56236. * Sets the length in pixels of the blur sample region
  56237. */
  56238. set: function (v) {
  56239. if (this._idealKernel === v) {
  56240. return;
  56241. }
  56242. v = Math.max(v, 1);
  56243. this._idealKernel = v;
  56244. this._kernel = this._nearestBestKernel(v);
  56245. this._updateParameters();
  56246. },
  56247. enumerable: true,
  56248. configurable: true
  56249. });
  56250. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  56251. /**
  56252. * Gets wether or not the blur is unpacking/repacking floats
  56253. */
  56254. get: function () {
  56255. return this._packedFloat;
  56256. },
  56257. /**
  56258. * Sets wether or not the blur needs to unpack/repack floats
  56259. */
  56260. set: function (v) {
  56261. if (this._packedFloat === v) {
  56262. return;
  56263. }
  56264. this._packedFloat = v;
  56265. this._updateParameters();
  56266. },
  56267. enumerable: true,
  56268. configurable: true
  56269. });
  56270. BlurPostProcess.prototype._updateParameters = function () {
  56271. // Generate sampling offsets and weights
  56272. var N = this._kernel;
  56273. var centerIndex = (N - 1) / 2;
  56274. // Generate Gaussian sampling weights over kernel
  56275. var offsets = [];
  56276. var weights = [];
  56277. var totalWeight = 0;
  56278. for (var i = 0; i < N; i++) {
  56279. var u = i / (N - 1);
  56280. var w = this._gaussianWeight(u * 2.0 - 1);
  56281. offsets[i] = (i - centerIndex);
  56282. weights[i] = w;
  56283. totalWeight += w;
  56284. }
  56285. // Normalize weights
  56286. for (var i = 0; i < weights.length; i++) {
  56287. weights[i] /= totalWeight;
  56288. }
  56289. // Optimize: combine samples to take advantage of hardware linear sampling
  56290. // Walk from left to center, combining pairs (symmetrically)
  56291. var linearSamplingWeights = [];
  56292. var linearSamplingOffsets = [];
  56293. var linearSamplingMap = [];
  56294. for (var i = 0; i <= centerIndex; i += 2) {
  56295. var j = Math.min(i + 1, Math.floor(centerIndex));
  56296. var singleCenterSample = i === j;
  56297. if (singleCenterSample) {
  56298. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56299. }
  56300. else {
  56301. var sharedCell = j === centerIndex;
  56302. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  56303. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  56304. if (offsetLinear === 0) {
  56305. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56306. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  56307. }
  56308. else {
  56309. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  56310. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  56311. }
  56312. }
  56313. }
  56314. for (var i = 0; i < linearSamplingMap.length; i++) {
  56315. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  56316. linearSamplingWeights[i] = linearSamplingMap[i].w;
  56317. }
  56318. // Replace with optimized
  56319. offsets = linearSamplingOffsets;
  56320. weights = linearSamplingWeights;
  56321. // Generate shaders
  56322. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  56323. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  56324. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  56325. var defines = "";
  56326. for (var i = 0; i < varyingCount; i++) {
  56327. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  56328. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  56329. }
  56330. var depCount = 0;
  56331. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  56332. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  56333. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  56334. depCount++;
  56335. }
  56336. if (this.packedFloat) {
  56337. defines += "#define PACKEDFLOAT 1";
  56338. }
  56339. this.updateEffect(defines, null, null, {
  56340. varyingCount: varyingCount,
  56341. depCount: depCount
  56342. });
  56343. };
  56344. /**
  56345. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  56346. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  56347. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  56348. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  56349. * The gaps between physical kernels are compensated for in the weighting of the samples
  56350. * @param idealKernel Ideal blur kernel.
  56351. * @return Nearest best kernel.
  56352. */
  56353. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  56354. var v = Math.round(idealKernel);
  56355. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  56356. var k = _a[_i];
  56357. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  56358. return Math.max(k, 3);
  56359. }
  56360. }
  56361. return Math.max(v, 3);
  56362. };
  56363. /**
  56364. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  56365. * @param x The point on the Gaussian distribution to sample.
  56366. * @return the value of the Gaussian function at x.
  56367. */
  56368. BlurPostProcess.prototype._gaussianWeight = function (x) {
  56369. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  56370. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  56371. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  56372. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  56373. // truncated at around 1.3% of peak strength.
  56374. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  56375. var sigma = (1 / 3);
  56376. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  56377. var exponent = -((x * x) / (2.0 * sigma * sigma));
  56378. var weight = (1.0 / denominator) * Math.exp(exponent);
  56379. return weight;
  56380. };
  56381. /**
  56382. * Generates a string that can be used as a floating point number in GLSL.
  56383. * @param x Value to print.
  56384. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  56385. * @return GLSL float string.
  56386. */
  56387. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  56388. if (decimalFigures === void 0) { decimalFigures = 8; }
  56389. return x.toFixed(decimalFigures).replace(/0+$/, '');
  56390. };
  56391. return BlurPostProcess;
  56392. }(BABYLON.PostProcess));
  56393. BABYLON.BlurPostProcess = BlurPostProcess;
  56394. })(BABYLON || (BABYLON = {}));
  56395. //# sourceMappingURL=babylon.blurPostProcess.js.map
  56396. /// <reference path="..\babylon.node.ts" />
  56397. var BABYLON;
  56398. (function (BABYLON) {
  56399. var Bone = (function (_super) {
  56400. __extends(Bone, _super);
  56401. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  56402. if (parentBone === void 0) { parentBone = null; }
  56403. var _this = _super.call(this, name, skeleton.getScene()) || this;
  56404. _this.name = name;
  56405. _this.children = new Array();
  56406. _this.animations = new Array();
  56407. _this._worldTransform = new BABYLON.Matrix();
  56408. _this._absoluteTransform = new BABYLON.Matrix();
  56409. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  56410. _this._scaleMatrix = BABYLON.Matrix.Identity();
  56411. _this._scaleVector = BABYLON.Vector3.One();
  56412. _this._negateScaleChildren = BABYLON.Vector3.One();
  56413. _this._scalingDeterminant = 1;
  56414. _this._skeleton = skeleton;
  56415. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  56416. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  56417. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  56418. _this._index = index;
  56419. skeleton.bones.push(_this);
  56420. _this.setParent(parentBone, false);
  56421. _this._updateDifferenceMatrix();
  56422. return _this;
  56423. }
  56424. Object.defineProperty(Bone.prototype, "_matrix", {
  56425. get: function () {
  56426. return this._localMatrix;
  56427. },
  56428. set: function (val) {
  56429. if (this._localMatrix) {
  56430. this._localMatrix.copyFrom(val);
  56431. }
  56432. else {
  56433. this._localMatrix = val;
  56434. }
  56435. },
  56436. enumerable: true,
  56437. configurable: true
  56438. });
  56439. // Members
  56440. Bone.prototype.getSkeleton = function () {
  56441. return this._skeleton;
  56442. };
  56443. Bone.prototype.getParent = function () {
  56444. return this._parent;
  56445. };
  56446. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  56447. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56448. if (this._parent === parent) {
  56449. return;
  56450. }
  56451. if (this._parent) {
  56452. var index = this._parent.children.indexOf(this);
  56453. if (index !== -1) {
  56454. this._parent.children.splice(index);
  56455. }
  56456. }
  56457. this._parent = parent;
  56458. if (this._parent) {
  56459. this._parent.children.push(this);
  56460. }
  56461. if (updateDifferenceMatrix) {
  56462. this._updateDifferenceMatrix();
  56463. }
  56464. };
  56465. Bone.prototype.getLocalMatrix = function () {
  56466. return this._localMatrix;
  56467. };
  56468. Bone.prototype.getBaseMatrix = function () {
  56469. return this._baseMatrix;
  56470. };
  56471. Bone.prototype.getRestPose = function () {
  56472. return this._restPose;
  56473. };
  56474. Bone.prototype.returnToRest = function () {
  56475. this.updateMatrix(this._restPose.clone());
  56476. };
  56477. Bone.prototype.getWorldMatrix = function () {
  56478. return this._worldTransform;
  56479. };
  56480. Bone.prototype.getInvertedAbsoluteTransform = function () {
  56481. return this._invertedAbsoluteTransform;
  56482. };
  56483. Bone.prototype.getAbsoluteTransform = function () {
  56484. return this._absoluteTransform;
  56485. };
  56486. Object.defineProperty(Bone.prototype, "position", {
  56487. // Properties (matches AbstractMesh properties)
  56488. get: function () {
  56489. return this.getPosition();
  56490. },
  56491. set: function (newPosition) {
  56492. this.setPosition(newPosition);
  56493. },
  56494. enumerable: true,
  56495. configurable: true
  56496. });
  56497. Object.defineProperty(Bone.prototype, "rotation", {
  56498. get: function () {
  56499. return this.getRotation();
  56500. },
  56501. set: function (newRotation) {
  56502. this.setRotation(newRotation);
  56503. },
  56504. enumerable: true,
  56505. configurable: true
  56506. });
  56507. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  56508. get: function () {
  56509. return this.getRotationQuaternion();
  56510. },
  56511. set: function (newRotation) {
  56512. this.setRotationQuaternion(newRotation);
  56513. },
  56514. enumerable: true,
  56515. configurable: true
  56516. });
  56517. Object.defineProperty(Bone.prototype, "scaling", {
  56518. get: function () {
  56519. return this.getScale();
  56520. },
  56521. set: function (newScaling) {
  56522. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  56523. },
  56524. enumerable: true,
  56525. configurable: true
  56526. });
  56527. // Methods
  56528. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  56529. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56530. this._baseMatrix = matrix.clone();
  56531. this._localMatrix = matrix.clone();
  56532. this._skeleton._markAsDirty();
  56533. if (updateDifferenceMatrix) {
  56534. this._updateDifferenceMatrix();
  56535. }
  56536. };
  56537. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  56538. if (!rootMatrix) {
  56539. rootMatrix = this._baseMatrix;
  56540. }
  56541. if (this._parent) {
  56542. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56543. }
  56544. else {
  56545. this._absoluteTransform.copyFrom(rootMatrix);
  56546. }
  56547. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  56548. for (var index = 0; index < this.children.length; index++) {
  56549. this.children[index]._updateDifferenceMatrix();
  56550. }
  56551. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  56552. };
  56553. Bone.prototype.markAsDirty = function () {
  56554. this._currentRenderId++;
  56555. this._skeleton._markAsDirty();
  56556. };
  56557. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  56558. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56559. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  56560. // all animation may be coming from a library skeleton, so may need to create animation
  56561. if (this.animations.length === 0) {
  56562. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  56563. this.animations[0].setKeys([]);
  56564. }
  56565. // get animation info / verify there is such a range from the source bone
  56566. var sourceRange = source.animations[0].getRange(rangeName);
  56567. if (!sourceRange) {
  56568. return false;
  56569. }
  56570. var from = sourceRange.from;
  56571. var to = sourceRange.to;
  56572. var sourceKeys = source.animations[0].getKeys();
  56573. // rescaling prep
  56574. var sourceBoneLength = source.length;
  56575. var sourceParent = source.getParent();
  56576. var parent = this.getParent();
  56577. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  56578. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  56579. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  56580. var destKeys = this.animations[0].getKeys();
  56581. // loop vars declaration
  56582. var orig;
  56583. var origTranslation;
  56584. var mat;
  56585. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  56586. orig = sourceKeys[key];
  56587. if (orig.frame >= from && orig.frame <= to) {
  56588. if (rescaleAsRequired) {
  56589. mat = orig.value.clone();
  56590. // scale based on parent ratio, when bone has parent
  56591. if (parentScalingReqd) {
  56592. origTranslation = mat.getTranslation();
  56593. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  56594. // scale based on skeleton dimension ratio when root bone, and value is passed
  56595. }
  56596. else if (dimensionsScalingReqd) {
  56597. origTranslation = mat.getTranslation();
  56598. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  56599. // use original when root bone, and no data for skelDimensionsRatio
  56600. }
  56601. else {
  56602. mat = orig.value;
  56603. }
  56604. }
  56605. else {
  56606. mat = orig.value;
  56607. }
  56608. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  56609. }
  56610. }
  56611. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  56612. return true;
  56613. };
  56614. /**
  56615. * Translate the bone in local or world space.
  56616. * @param vec The amount to translate the bone.
  56617. * @param space The space that the translation is in.
  56618. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56619. */
  56620. Bone.prototype.translate = function (vec, space, mesh) {
  56621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56622. var lm = this.getLocalMatrix();
  56623. if (space == BABYLON.Space.LOCAL) {
  56624. lm.m[12] += vec.x;
  56625. lm.m[13] += vec.y;
  56626. lm.m[14] += vec.z;
  56627. }
  56628. else {
  56629. var wm;
  56630. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56631. if (mesh) {
  56632. wm = mesh.getWorldMatrix();
  56633. }
  56634. this._skeleton.computeAbsoluteTransforms();
  56635. var tmat = Bone._tmpMats[0];
  56636. var tvec = Bone._tmpVecs[0];
  56637. if (mesh) {
  56638. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56639. tmat.multiplyToRef(wm, tmat);
  56640. }
  56641. else {
  56642. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56643. }
  56644. tmat.m[12] = 0;
  56645. tmat.m[13] = 0;
  56646. tmat.m[14] = 0;
  56647. tmat.invert();
  56648. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  56649. lm.m[12] += tvec.x;
  56650. lm.m[13] += tvec.y;
  56651. lm.m[14] += tvec.z;
  56652. }
  56653. this.markAsDirty();
  56654. };
  56655. /**
  56656. * Set the postion of the bone in local or world space.
  56657. * @param position The position to set the bone.
  56658. * @param space The space that the position is in.
  56659. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56660. */
  56661. Bone.prototype.setPosition = function (position, space, mesh) {
  56662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56663. var lm = this.getLocalMatrix();
  56664. if (space == BABYLON.Space.LOCAL) {
  56665. lm.m[12] = position.x;
  56666. lm.m[13] = position.y;
  56667. lm.m[14] = position.z;
  56668. }
  56669. else {
  56670. var wm;
  56671. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56672. if (mesh) {
  56673. wm = mesh.getWorldMatrix();
  56674. }
  56675. this._skeleton.computeAbsoluteTransforms();
  56676. var tmat = Bone._tmpMats[0];
  56677. var vec = Bone._tmpVecs[0];
  56678. if (mesh) {
  56679. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56680. tmat.multiplyToRef(wm, tmat);
  56681. }
  56682. else {
  56683. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56684. }
  56685. tmat.invert();
  56686. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  56687. lm.m[12] = vec.x;
  56688. lm.m[13] = vec.y;
  56689. lm.m[14] = vec.z;
  56690. }
  56691. this.markAsDirty();
  56692. };
  56693. /**
  56694. * Set the absolute postion of the bone (world space).
  56695. * @param position The position to set the bone.
  56696. * @param mesh The mesh that this bone is attached to.
  56697. */
  56698. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  56699. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  56700. };
  56701. /**
  56702. * Set the scale of the bone on the x, y and z axes.
  56703. * @param x The scale of the bone on the x axis.
  56704. * @param x The scale of the bone on the y axis.
  56705. * @param z The scale of the bone on the z axis.
  56706. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56707. */
  56708. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  56709. if (scaleChildren === void 0) { scaleChildren = false; }
  56710. if (this.animations[0] && !this.animations[0].isStopped()) {
  56711. if (!scaleChildren) {
  56712. this._negateScaleChildren.x = 1 / x;
  56713. this._negateScaleChildren.y = 1 / y;
  56714. this._negateScaleChildren.z = 1 / z;
  56715. }
  56716. this._syncScaleVector();
  56717. }
  56718. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  56719. };
  56720. /**
  56721. * Scale the bone on the x, y and z axes.
  56722. * @param x The amount to scale the bone on the x axis.
  56723. * @param x The amount to scale the bone on the y axis.
  56724. * @param z The amount to scale the bone on the z axis.
  56725. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56726. */
  56727. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  56728. if (scaleChildren === void 0) { scaleChildren = false; }
  56729. var locMat = this.getLocalMatrix();
  56730. var origLocMat = Bone._tmpMats[0];
  56731. origLocMat.copyFrom(locMat);
  56732. var origLocMatInv = Bone._tmpMats[1];
  56733. origLocMatInv.copyFrom(origLocMat);
  56734. origLocMatInv.invert();
  56735. var scaleMat = Bone._tmpMats[2];
  56736. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  56737. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  56738. this._scaleVector.x *= x;
  56739. this._scaleVector.y *= y;
  56740. this._scaleVector.z *= z;
  56741. locMat.multiplyToRef(origLocMatInv, locMat);
  56742. locMat.multiplyToRef(scaleMat, locMat);
  56743. locMat.multiplyToRef(origLocMat, locMat);
  56744. var parent = this.getParent();
  56745. if (parent) {
  56746. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  56747. }
  56748. else {
  56749. this.getAbsoluteTransform().copyFrom(locMat);
  56750. }
  56751. var len = this.children.length;
  56752. scaleMat.invert();
  56753. for (var i = 0; i < len; i++) {
  56754. var child = this.children[i];
  56755. var cm = child.getLocalMatrix();
  56756. cm.multiplyToRef(scaleMat, cm);
  56757. var lm = child.getLocalMatrix();
  56758. lm.m[12] *= x;
  56759. lm.m[13] *= y;
  56760. lm.m[14] *= z;
  56761. }
  56762. this.computeAbsoluteTransforms();
  56763. if (scaleChildren) {
  56764. for (var i = 0; i < len; i++) {
  56765. this.children[i].scale(x, y, z, scaleChildren);
  56766. }
  56767. }
  56768. this.markAsDirty();
  56769. };
  56770. /**
  56771. * Set the yaw, pitch, and roll of the bone in local or world space.
  56772. * @param yaw The rotation of the bone on the y axis.
  56773. * @param pitch The rotation of the bone on the x axis.
  56774. * @param roll The rotation of the bone on the z axis.
  56775. * @param space The space that the axes of rotation are in.
  56776. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56777. */
  56778. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  56779. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56780. var rotMat = Bone._tmpMats[0];
  56781. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  56782. var rotMatInv = Bone._tmpMats[1];
  56783. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56784. rotMatInv.multiplyToRef(rotMat, rotMat);
  56785. this._rotateWithMatrix(rotMat, space, mesh);
  56786. };
  56787. /**
  56788. * Rotate the bone on an axis in local or world space.
  56789. * @param axis The axis to rotate the bone on.
  56790. * @param amount The amount to rotate the bone.
  56791. * @param space The space that the axis is in.
  56792. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56793. */
  56794. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  56795. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56796. var rmat = Bone._tmpMats[0];
  56797. rmat.m[12] = 0;
  56798. rmat.m[13] = 0;
  56799. rmat.m[14] = 0;
  56800. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  56801. this._rotateWithMatrix(rmat, space, mesh);
  56802. };
  56803. /**
  56804. * Set the rotation of the bone to a particular axis angle in local or world space.
  56805. * @param axis The axis to rotate the bone on.
  56806. * @param angle The angle that the bone should be rotated to.
  56807. * @param space The space that the axis is in.
  56808. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56809. */
  56810. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  56811. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56812. var rotMat = Bone._tmpMats[0];
  56813. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  56814. var rotMatInv = Bone._tmpMats[1];
  56815. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56816. rotMatInv.multiplyToRef(rotMat, rotMat);
  56817. this._rotateWithMatrix(rotMat, space, mesh);
  56818. };
  56819. /**
  56820. * Set the euler rotation of the bone in local of world space.
  56821. * @param rotation The euler rotation that the bone should be set to.
  56822. * @param space The space that the rotation is in.
  56823. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56824. */
  56825. Bone.prototype.setRotation = function (rotation, space, mesh) {
  56826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56827. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  56828. };
  56829. /**
  56830. * Set the quaternion rotation of the bone in local of world space.
  56831. * @param quat The quaternion rotation that the bone should be set to.
  56832. * @param space The space that the rotation is in.
  56833. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56834. */
  56835. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  56836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56837. var rotMatInv = Bone._tmpMats[0];
  56838. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56839. var rotMat = Bone._tmpMats[1];
  56840. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  56841. rotMatInv.multiplyToRef(rotMat, rotMat);
  56842. this._rotateWithMatrix(rotMat, space, mesh);
  56843. };
  56844. /**
  56845. * Set the rotation matrix of the bone in local of world space.
  56846. * @param rotMat The rotation matrix that the bone should be set to.
  56847. * @param space The space that the rotation is in.
  56848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56849. */
  56850. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  56851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56852. var rotMatInv = Bone._tmpMats[0];
  56853. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56854. var rotMat2 = Bone._tmpMats[1];
  56855. rotMat2.copyFrom(rotMat);
  56856. rotMatInv.multiplyToRef(rotMat, rotMat2);
  56857. this._rotateWithMatrix(rotMat2, space, mesh);
  56858. };
  56859. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  56860. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56861. var lmat = this.getLocalMatrix();
  56862. var lx = lmat.m[12];
  56863. var ly = lmat.m[13];
  56864. var lz = lmat.m[14];
  56865. var parent = this.getParent();
  56866. var parentScale = Bone._tmpMats[3];
  56867. var parentScaleInv = Bone._tmpMats[4];
  56868. if (parent) {
  56869. if (space == BABYLON.Space.WORLD) {
  56870. if (mesh) {
  56871. parentScale.copyFrom(mesh.getWorldMatrix());
  56872. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  56873. }
  56874. else {
  56875. parentScale.copyFrom(parent.getAbsoluteTransform());
  56876. }
  56877. }
  56878. else {
  56879. parentScale = parent._scaleMatrix;
  56880. }
  56881. parentScaleInv.copyFrom(parentScale);
  56882. parentScaleInv.invert();
  56883. lmat.multiplyToRef(parentScale, lmat);
  56884. lmat.multiplyToRef(rmat, lmat);
  56885. lmat.multiplyToRef(parentScaleInv, lmat);
  56886. }
  56887. else {
  56888. if (space == BABYLON.Space.WORLD && mesh) {
  56889. parentScale.copyFrom(mesh.getWorldMatrix());
  56890. parentScaleInv.copyFrom(parentScale);
  56891. parentScaleInv.invert();
  56892. lmat.multiplyToRef(parentScale, lmat);
  56893. lmat.multiplyToRef(rmat, lmat);
  56894. lmat.multiplyToRef(parentScaleInv, lmat);
  56895. }
  56896. else {
  56897. lmat.multiplyToRef(rmat, lmat);
  56898. }
  56899. }
  56900. lmat.m[12] = lx;
  56901. lmat.m[13] = ly;
  56902. lmat.m[14] = lz;
  56903. this.computeAbsoluteTransforms();
  56904. this.markAsDirty();
  56905. };
  56906. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  56907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56908. if (space == BABYLON.Space.WORLD) {
  56909. var scaleMatrix = Bone._tmpMats[2];
  56910. scaleMatrix.copyFrom(this._scaleMatrix);
  56911. rotMatInv.copyFrom(this.getAbsoluteTransform());
  56912. if (mesh) {
  56913. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  56914. var meshScale = Bone._tmpMats[3];
  56915. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  56916. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  56917. }
  56918. rotMatInv.invert();
  56919. scaleMatrix.m[0] *= this._scalingDeterminant;
  56920. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56921. }
  56922. else {
  56923. rotMatInv.copyFrom(this.getLocalMatrix());
  56924. rotMatInv.invert();
  56925. var scaleMatrix = Bone._tmpMats[2];
  56926. scaleMatrix.copyFrom(this._scaleMatrix);
  56927. if (this._parent) {
  56928. var pscaleMatrix = Bone._tmpMats[3];
  56929. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  56930. pscaleMatrix.invert();
  56931. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  56932. }
  56933. else {
  56934. scaleMatrix.m[0] *= this._scalingDeterminant;
  56935. }
  56936. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56937. }
  56938. };
  56939. /**
  56940. * Get the scale of the bone
  56941. * @returns the scale of the bone
  56942. */
  56943. Bone.prototype.getScale = function () {
  56944. return this._scaleVector.clone();
  56945. };
  56946. /**
  56947. * Copy the scale of the bone to a vector3.
  56948. * @param result The vector3 to copy the scale to
  56949. */
  56950. Bone.prototype.getScaleToRef = function (result) {
  56951. result.copyFrom(this._scaleVector);
  56952. };
  56953. /**
  56954. * Get the position of the bone in local or world space.
  56955. * @param space The space that the returned position is in.
  56956. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56957. * @returns The position of the bone
  56958. */
  56959. Bone.prototype.getPosition = function (space, mesh) {
  56960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56961. var pos = BABYLON.Vector3.Zero();
  56962. this.getPositionToRef(space, mesh, pos);
  56963. return pos;
  56964. };
  56965. /**
  56966. * Copy the position of the bone to a vector3 in local or world space.
  56967. * @param space The space that the returned position is in.
  56968. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56969. * @param result The vector3 to copy the position to.
  56970. */
  56971. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  56972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56973. if (space == BABYLON.Space.LOCAL) {
  56974. var lm = this.getLocalMatrix();
  56975. result.x = lm.m[12];
  56976. result.y = lm.m[13];
  56977. result.z = lm.m[14];
  56978. }
  56979. else {
  56980. var wm;
  56981. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56982. if (mesh) {
  56983. wm = mesh.getWorldMatrix();
  56984. }
  56985. this._skeleton.computeAbsoluteTransforms();
  56986. var tmat = Bone._tmpMats[0];
  56987. if (mesh) {
  56988. tmat.copyFrom(this.getAbsoluteTransform());
  56989. tmat.multiplyToRef(wm, tmat);
  56990. }
  56991. else {
  56992. tmat = this.getAbsoluteTransform();
  56993. }
  56994. result.x = tmat.m[12];
  56995. result.y = tmat.m[13];
  56996. result.z = tmat.m[14];
  56997. }
  56998. };
  56999. /**
  57000. * Get the absolute position of the bone (world space).
  57001. * @param mesh The mesh that this bone is attached to.
  57002. * @returns The absolute position of the bone
  57003. */
  57004. Bone.prototype.getAbsolutePosition = function (mesh) {
  57005. var pos = BABYLON.Vector3.Zero();
  57006. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  57007. return pos;
  57008. };
  57009. /**
  57010. * Copy the absolute position of the bone (world space) to the result param.
  57011. * @param mesh The mesh that this bone is attached to.
  57012. * @param result The vector3 to copy the absolute position to.
  57013. */
  57014. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  57015. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  57016. };
  57017. /**
  57018. * Compute the absolute transforms of this bone and its children.
  57019. */
  57020. Bone.prototype.computeAbsoluteTransforms = function () {
  57021. if (this._parent) {
  57022. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57023. }
  57024. else {
  57025. this._absoluteTransform.copyFrom(this._localMatrix);
  57026. var poseMatrix = this._skeleton.getPoseMatrix();
  57027. if (poseMatrix) {
  57028. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  57029. }
  57030. }
  57031. var children = this.children;
  57032. var len = children.length;
  57033. for (var i = 0; i < len; i++) {
  57034. children[i].computeAbsoluteTransforms();
  57035. }
  57036. };
  57037. Bone.prototype._syncScaleVector = function () {
  57038. var lm = this.getLocalMatrix();
  57039. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  57040. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  57041. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  57042. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  57043. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  57044. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  57045. this._scaleVector.x = xs * Math.sqrt(xsq);
  57046. this._scaleVector.y = ys * Math.sqrt(ysq);
  57047. this._scaleVector.z = zs * Math.sqrt(zsq);
  57048. if (this._parent) {
  57049. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  57050. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  57051. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  57052. }
  57053. 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);
  57054. };
  57055. /**
  57056. * Get the world direction from an axis that is in the local space of the bone.
  57057. * @param localAxis The local direction that is used to compute the world direction.
  57058. * @param mesh The mesh that this bone is attached to.
  57059. * @returns The world direction
  57060. */
  57061. Bone.prototype.getDirection = function (localAxis, mesh) {
  57062. var result = BABYLON.Vector3.Zero();
  57063. this.getDirectionToRef(localAxis, mesh, result);
  57064. return result;
  57065. };
  57066. /**
  57067. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  57068. * @param localAxis The local direction that is used to compute the world direction.
  57069. * @param mesh The mesh that this bone is attached to.
  57070. * @param result The vector3 that the world direction will be copied to.
  57071. */
  57072. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  57073. var wm;
  57074. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57075. if (mesh) {
  57076. wm = mesh.getWorldMatrix();
  57077. }
  57078. this._skeleton.computeAbsoluteTransforms();
  57079. var mat = Bone._tmpMats[0];
  57080. mat.copyFrom(this.getAbsoluteTransform());
  57081. if (mesh) {
  57082. mat.multiplyToRef(wm, mat);
  57083. }
  57084. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  57085. result.normalize();
  57086. };
  57087. /**
  57088. * Get the euler rotation of the bone in local or world space.
  57089. * @param space The space that the rotation should be in.
  57090. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57091. * @returns The euler rotation
  57092. */
  57093. Bone.prototype.getRotation = function (space, mesh) {
  57094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57095. var result = BABYLON.Vector3.Zero();
  57096. this.getRotationToRef(space, mesh, result);
  57097. return result;
  57098. };
  57099. /**
  57100. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  57101. * @param space The space that the rotation should be in.
  57102. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57103. * @param result The vector3 that the rotation should be copied to.
  57104. */
  57105. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  57106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57107. var quat = Bone._tmpQuat;
  57108. this.getRotationQuaternionToRef(space, mesh, quat);
  57109. quat.toEulerAnglesToRef(result);
  57110. };
  57111. /**
  57112. * Get the quaternion rotation of the bone in either local or world space.
  57113. * @param space The space that the rotation should be in.
  57114. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57115. * @returns The quaternion rotation
  57116. */
  57117. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  57118. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57119. var result = BABYLON.Quaternion.Identity();
  57120. this.getRotationQuaternionToRef(space, mesh, result);
  57121. return result;
  57122. };
  57123. /**
  57124. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  57125. * @param space The space that the rotation should be in.
  57126. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57127. * @param result The quaternion that the rotation should be copied to.
  57128. */
  57129. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  57130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57131. if (space == BABYLON.Space.LOCAL) {
  57132. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57133. }
  57134. else {
  57135. var mat = Bone._tmpMats[0];
  57136. var amat = this.getAbsoluteTransform();
  57137. if (mesh) {
  57138. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57139. }
  57140. else {
  57141. mat.copyFrom(amat);
  57142. }
  57143. mat.m[0] *= this._scalingDeterminant;
  57144. mat.m[1] *= this._scalingDeterminant;
  57145. mat.m[2] *= this._scalingDeterminant;
  57146. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57147. }
  57148. };
  57149. /**
  57150. * Get the rotation matrix of the bone in local or world space.
  57151. * @param space The space that the rotation should be in.
  57152. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57153. * @returns The rotation matrix
  57154. */
  57155. Bone.prototype.getRotationMatrix = function (space, mesh) {
  57156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57157. var result = BABYLON.Matrix.Identity();
  57158. this.getRotationMatrixToRef(space, mesh, result);
  57159. return result;
  57160. };
  57161. /**
  57162. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  57163. * @param space The space that the rotation should be in.
  57164. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57165. * @param result The quaternion that the rotation should be copied to.
  57166. */
  57167. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  57168. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57169. if (space == BABYLON.Space.LOCAL) {
  57170. this.getLocalMatrix().getRotationMatrixToRef(result);
  57171. }
  57172. else {
  57173. var mat = Bone._tmpMats[0];
  57174. var amat = this.getAbsoluteTransform();
  57175. if (mesh) {
  57176. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57177. }
  57178. else {
  57179. mat.copyFrom(amat);
  57180. }
  57181. mat.m[0] *= this._scalingDeterminant;
  57182. mat.m[1] *= this._scalingDeterminant;
  57183. mat.m[2] *= this._scalingDeterminant;
  57184. mat.getRotationMatrixToRef(result);
  57185. }
  57186. };
  57187. /**
  57188. * Get the world position of a point that is in the local space of the bone.
  57189. * @param position The local position
  57190. * @param mesh The mesh that this bone is attached to.
  57191. * @returns The world position
  57192. */
  57193. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  57194. var result = BABYLON.Vector3.Zero();
  57195. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  57196. return result;
  57197. };
  57198. /**
  57199. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  57200. * @param position The local position
  57201. * @param mesh The mesh that this bone is attached to.
  57202. * @param result The vector3 that the world position should be copied to.
  57203. */
  57204. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  57205. var wm;
  57206. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57207. if (mesh) {
  57208. wm = mesh.getWorldMatrix();
  57209. }
  57210. this._skeleton.computeAbsoluteTransforms();
  57211. var tmat = Bone._tmpMats[0];
  57212. if (mesh) {
  57213. tmat.copyFrom(this.getAbsoluteTransform());
  57214. tmat.multiplyToRef(wm, tmat);
  57215. }
  57216. else {
  57217. tmat = this.getAbsoluteTransform();
  57218. }
  57219. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57220. };
  57221. /**
  57222. * Get the local position of a point that is in world space.
  57223. * @param position The world position
  57224. * @param mesh The mesh that this bone is attached to.
  57225. * @returns The local position
  57226. */
  57227. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  57228. var result = BABYLON.Vector3.Zero();
  57229. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  57230. return result;
  57231. };
  57232. /**
  57233. * Get the local position of a point that is in world space and copy it to the result param.
  57234. * @param position The world position
  57235. * @param mesh The mesh that this bone is attached to.
  57236. * @param result The vector3 that the local position should be copied to.
  57237. */
  57238. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  57239. var wm;
  57240. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57241. if (mesh) {
  57242. wm = mesh.getWorldMatrix();
  57243. }
  57244. this._skeleton.computeAbsoluteTransforms();
  57245. var tmat = Bone._tmpMats[0];
  57246. tmat.copyFrom(this.getAbsoluteTransform());
  57247. if (mesh) {
  57248. tmat.multiplyToRef(wm, tmat);
  57249. }
  57250. tmat.invert();
  57251. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57252. };
  57253. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57254. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  57255. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57256. return Bone;
  57257. }(BABYLON.Node));
  57258. BABYLON.Bone = Bone;
  57259. })(BABYLON || (BABYLON = {}));
  57260. //# sourceMappingURL=babylon.bone.js.map
  57261. var BABYLON;
  57262. (function (BABYLON) {
  57263. var BoneIKController = (function () {
  57264. function BoneIKController(mesh, bone, options) {
  57265. this.targetPosition = BABYLON.Vector3.Zero();
  57266. this.poleTargetPosition = BABYLON.Vector3.Zero();
  57267. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  57268. this.poleAngle = 0;
  57269. this.slerpAmount = 1;
  57270. this._bone1Quat = BABYLON.Quaternion.Identity();
  57271. this._bone1Mat = BABYLON.Matrix.Identity();
  57272. this._bone2Ang = Math.PI;
  57273. this._maxAngle = Math.PI;
  57274. this._rightHandedSystem = false;
  57275. this._bendAxis = BABYLON.Vector3.Right();
  57276. this._slerping = false;
  57277. this._adjustRoll = 0;
  57278. this._bone2 = bone;
  57279. this._bone1 = bone.getParent();
  57280. this.mesh = mesh;
  57281. var bonePos = bone.getPosition();
  57282. if (bone.getAbsoluteTransform().determinant() > 0) {
  57283. this._rightHandedSystem = true;
  57284. this._bendAxis.x = 0;
  57285. this._bendAxis.y = 0;
  57286. this._bendAxis.z = -1;
  57287. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  57288. this._adjustRoll = Math.PI * .5;
  57289. this._bendAxis.z = 1;
  57290. }
  57291. }
  57292. if (this._bone1.length) {
  57293. var boneScale1 = this._bone1.getScale();
  57294. var boneScale2 = this._bone2.getScale();
  57295. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  57296. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  57297. }
  57298. else if (this._bone1.children[0]) {
  57299. mesh.computeWorldMatrix(true);
  57300. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  57301. var pos2 = this._bone2.getAbsolutePosition(mesh);
  57302. var pos3 = this._bone1.getAbsolutePosition(mesh);
  57303. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  57304. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  57305. }
  57306. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  57307. this.maxAngle = Math.PI;
  57308. if (options) {
  57309. if (options.targetMesh) {
  57310. this.targetMesh = options.targetMesh;
  57311. this.targetMesh.computeWorldMatrix(true);
  57312. }
  57313. if (options.poleTargetMesh) {
  57314. this.poleTargetMesh = options.poleTargetMesh;
  57315. this.poleTargetMesh.computeWorldMatrix(true);
  57316. }
  57317. else if (options.poleTargetBone) {
  57318. this.poleTargetBone = options.poleTargetBone;
  57319. }
  57320. else if (this._bone1.getParent()) {
  57321. this.poleTargetBone = this._bone1.getParent();
  57322. }
  57323. if (options.poleTargetLocalOffset) {
  57324. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  57325. }
  57326. if (options.poleAngle) {
  57327. this.poleAngle = options.poleAngle;
  57328. }
  57329. if (options.bendAxis) {
  57330. this._bendAxis.copyFrom(options.bendAxis);
  57331. }
  57332. if (options.maxAngle) {
  57333. this.maxAngle = options.maxAngle;
  57334. }
  57335. if (options.slerpAmount) {
  57336. this.slerpAmount = options.slerpAmount;
  57337. }
  57338. }
  57339. }
  57340. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  57341. get: function () {
  57342. return this._maxAngle;
  57343. },
  57344. set: function (value) {
  57345. this._setMaxAngle(value);
  57346. },
  57347. enumerable: true,
  57348. configurable: true
  57349. });
  57350. BoneIKController.prototype._setMaxAngle = function (ang) {
  57351. if (ang < 0) {
  57352. ang = 0;
  57353. }
  57354. if (ang > Math.PI || ang == undefined) {
  57355. ang = Math.PI;
  57356. }
  57357. this._maxAngle = ang;
  57358. var a = this._bone1Length;
  57359. var b = this._bone2Length;
  57360. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  57361. };
  57362. BoneIKController.prototype.update = function () {
  57363. var bone1 = this._bone1;
  57364. var target = this.targetPosition;
  57365. var poleTarget = this.poleTargetPosition;
  57366. var mat1 = BoneIKController._tmpMats[0];
  57367. var mat2 = BoneIKController._tmpMats[1];
  57368. if (this.targetMesh) {
  57369. target.copyFrom(this.targetMesh.getAbsolutePosition());
  57370. }
  57371. if (this.poleTargetBone) {
  57372. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  57373. }
  57374. else if (this.poleTargetMesh) {
  57375. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  57376. }
  57377. var bonePos = BoneIKController._tmpVecs[0];
  57378. var zaxis = BoneIKController._tmpVecs[1];
  57379. var xaxis = BoneIKController._tmpVecs[2];
  57380. var yaxis = BoneIKController._tmpVecs[3];
  57381. var upAxis = BoneIKController._tmpVecs[4];
  57382. var _tmpQuat = BoneIKController._tmpQuat;
  57383. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  57384. poleTarget.subtractToRef(bonePos, upAxis);
  57385. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  57386. upAxis.y = 1;
  57387. }
  57388. else {
  57389. upAxis.normalize();
  57390. }
  57391. target.subtractToRef(bonePos, yaxis);
  57392. yaxis.normalize();
  57393. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  57394. zaxis.normalize();
  57395. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  57396. xaxis.normalize();
  57397. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  57398. var a = this._bone1Length;
  57399. var b = this._bone2Length;
  57400. var c = BABYLON.Vector3.Distance(bonePos, target);
  57401. if (this._maxReach > 0) {
  57402. c = Math.min(this._maxReach, c);
  57403. }
  57404. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  57405. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  57406. if (acosa > 1) {
  57407. acosa = 1;
  57408. }
  57409. if (acosb > 1) {
  57410. acosb = 1;
  57411. }
  57412. if (acosa < -1) {
  57413. acosa = -1;
  57414. }
  57415. if (acosb < -1) {
  57416. acosb = -1;
  57417. }
  57418. var angA = Math.acos(acosa);
  57419. var angB = Math.acos(acosb);
  57420. var angC = -angA - angB;
  57421. if (this._rightHandedSystem) {
  57422. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  57423. mat2.multiplyToRef(mat1, mat1);
  57424. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  57425. mat2.multiplyToRef(mat1, mat1);
  57426. }
  57427. else {
  57428. var _tmpVec = BoneIKController._tmpVecs[5];
  57429. _tmpVec.copyFrom(this._bendAxis);
  57430. _tmpVec.x *= -1;
  57431. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  57432. mat2.multiplyToRef(mat1, mat1);
  57433. }
  57434. if (this.poleAngle) {
  57435. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  57436. mat1.multiplyToRef(mat2, mat1);
  57437. }
  57438. if (this.slerpAmount < 1) {
  57439. if (!this._slerping) {
  57440. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  57441. }
  57442. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  57443. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  57444. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  57445. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  57446. this._slerping = true;
  57447. }
  57448. else {
  57449. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  57450. this._bone1Mat.copyFrom(mat1);
  57451. this._slerping = false;
  57452. }
  57453. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  57454. this._bone2Ang = angC;
  57455. };
  57456. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57457. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  57458. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57459. return BoneIKController;
  57460. }());
  57461. BABYLON.BoneIKController = BoneIKController;
  57462. })(BABYLON || (BABYLON = {}));
  57463. //# sourceMappingURL=babylon.boneIKController.js.map
  57464. var BABYLON;
  57465. (function (BABYLON) {
  57466. var BoneLookController = (function () {
  57467. /**
  57468. * Create a BoneLookController
  57469. * @param mesh the mesh that the bone belongs to
  57470. * @param bone the bone that will be looking to the target
  57471. * @param target the target Vector3 to look at
  57472. * @param settings optional settings:
  57473. * - maxYaw: the maximum angle the bone will yaw to
  57474. * - minYaw: the minimum angle the bone will yaw to
  57475. * - maxPitch: the maximum angle the bone will pitch to
  57476. * - minPitch: the minimum angle the bone will yaw to
  57477. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  57478. * - upAxis: the up axis of the coordinate system
  57479. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57480. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  57481. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  57482. * - adjustYaw: used to make an adjustment to the yaw of the bone
  57483. * - adjustPitch: used to make an adjustment to the pitch of the bone
  57484. * - adjustRoll: used to make an adjustment to the roll of the bone
  57485. **/
  57486. function BoneLookController(mesh, bone, target, options) {
  57487. /**
  57488. * The up axis of the coordinate system that is used when the bone is rotated.
  57489. */
  57490. this.upAxis = BABYLON.Vector3.Up();
  57491. /**
  57492. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57493. */
  57494. this.upAxisSpace = BABYLON.Space.LOCAL;
  57495. /**
  57496. * Used to make an adjustment to the yaw of the bone.
  57497. */
  57498. this.adjustYaw = 0;
  57499. /**
  57500. * Used to make an adjustment to the pitch of the bone.
  57501. */
  57502. this.adjustPitch = 0;
  57503. /**
  57504. * Used to make an adjustment to the roll of the bone.
  57505. */
  57506. this.adjustRoll = 0;
  57507. /**
  57508. * 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).
  57509. */
  57510. this.slerpAmount = 1;
  57511. this._boneQuat = BABYLON.Quaternion.Identity();
  57512. this._slerping = false;
  57513. this._firstFrameSkipped = false;
  57514. this._fowardAxis = BABYLON.Vector3.Forward();
  57515. this.mesh = mesh;
  57516. this.bone = bone;
  57517. this.target = target;
  57518. if (options) {
  57519. if (options.adjustYaw) {
  57520. this.adjustYaw = options.adjustYaw;
  57521. }
  57522. if (options.adjustPitch) {
  57523. this.adjustPitch = options.adjustPitch;
  57524. }
  57525. if (options.adjustRoll) {
  57526. this.adjustRoll = options.adjustRoll;
  57527. }
  57528. if (options.maxYaw != null) {
  57529. this.maxYaw = options.maxYaw;
  57530. }
  57531. else {
  57532. this.maxYaw = Math.PI;
  57533. }
  57534. if (options.minYaw != null) {
  57535. this.minYaw = options.minYaw;
  57536. }
  57537. else {
  57538. this.minYaw = -Math.PI;
  57539. }
  57540. if (options.maxPitch != null) {
  57541. this.maxPitch = options.maxPitch;
  57542. }
  57543. else {
  57544. this.maxPitch = Math.PI;
  57545. }
  57546. if (options.minPitch != null) {
  57547. this.minPitch = options.minPitch;
  57548. }
  57549. else {
  57550. this.minPitch = -Math.PI;
  57551. }
  57552. if (options.slerpAmount != null) {
  57553. this.slerpAmount = options.slerpAmount;
  57554. }
  57555. if (options.upAxis != null) {
  57556. this.upAxis = options.upAxis;
  57557. }
  57558. if (options.upAxisSpace != null) {
  57559. this.upAxisSpace = options.upAxisSpace;
  57560. }
  57561. if (options.yawAxis != null || options.pitchAxis != null) {
  57562. var newYawAxis = BABYLON.Axis.Y;
  57563. var newPitchAxis = BABYLON.Axis.X;
  57564. if (options.yawAxis != null) {
  57565. newYawAxis = options.yawAxis.clone();
  57566. newYawAxis.normalize();
  57567. }
  57568. if (options.pitchAxis != null) {
  57569. newPitchAxis = options.pitchAxis.clone();
  57570. newPitchAxis.normalize();
  57571. }
  57572. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  57573. this._transformYawPitch = BABYLON.Matrix.Identity();
  57574. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  57575. this._transformYawPitchInv = this._transformYawPitch.clone();
  57576. this._transformYawPitch.invert();
  57577. }
  57578. }
  57579. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  57580. this.upAxisSpace = BABYLON.Space.LOCAL;
  57581. }
  57582. }
  57583. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  57584. /**
  57585. * Get/set the minimum yaw angle that the bone can look to.
  57586. */
  57587. get: function () {
  57588. return this._minYaw;
  57589. },
  57590. set: function (value) {
  57591. this._minYaw = value;
  57592. this._minYawSin = Math.sin(value);
  57593. this._minYawCos = Math.cos(value);
  57594. if (this._maxYaw != null) {
  57595. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57596. this._yawRange = this._maxYaw - this._minYaw;
  57597. }
  57598. },
  57599. enumerable: true,
  57600. configurable: true
  57601. });
  57602. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  57603. /**
  57604. * Get/set the maximum yaw angle that the bone can look to.
  57605. */
  57606. get: function () {
  57607. return this._maxYaw;
  57608. },
  57609. set: function (value) {
  57610. this._maxYaw = value;
  57611. this._maxYawSin = Math.sin(value);
  57612. this._maxYawCos = Math.cos(value);
  57613. if (this._minYaw != null) {
  57614. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57615. this._yawRange = this._maxYaw - this._minYaw;
  57616. }
  57617. },
  57618. enumerable: true,
  57619. configurable: true
  57620. });
  57621. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  57622. /**
  57623. * Get/set the minimum pitch angle that the bone can look to.
  57624. */
  57625. get: function () {
  57626. return this._minPitch;
  57627. },
  57628. set: function (value) {
  57629. this._minPitch = value;
  57630. this._minPitchTan = Math.tan(value);
  57631. },
  57632. enumerable: true,
  57633. configurable: true
  57634. });
  57635. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  57636. /**
  57637. * Get/set the maximum pitch angle that the bone can look to.
  57638. */
  57639. get: function () {
  57640. return this._maxPitch;
  57641. },
  57642. set: function (value) {
  57643. this._maxPitch = value;
  57644. this._maxPitchTan = Math.tan(value);
  57645. },
  57646. enumerable: true,
  57647. configurable: true
  57648. });
  57649. /**
  57650. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  57651. */
  57652. BoneLookController.prototype.update = function () {
  57653. //skip the first frame when slerping so that the mesh rotation is correct
  57654. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  57655. this._firstFrameSkipped = true;
  57656. return;
  57657. }
  57658. var bone = this.bone;
  57659. var bonePos = BoneLookController._tmpVecs[0];
  57660. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  57661. var target = this.target;
  57662. var _tmpMat1 = BoneLookController._tmpMats[0];
  57663. var _tmpMat2 = BoneLookController._tmpMats[1];
  57664. var mesh = this.mesh;
  57665. var parentBone = bone.getParent();
  57666. var upAxis = BoneLookController._tmpVecs[1];
  57667. upAxis.copyFrom(this.upAxis);
  57668. if (this.upAxisSpace == BABYLON.Space.BONE) {
  57669. if (this._transformYawPitch) {
  57670. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  57671. }
  57672. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  57673. }
  57674. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  57675. mesh.getDirectionToRef(upAxis, upAxis);
  57676. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  57677. upAxis.normalize();
  57678. }
  57679. }
  57680. var checkYaw = false;
  57681. var checkPitch = false;
  57682. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  57683. checkYaw = true;
  57684. }
  57685. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  57686. checkPitch = true;
  57687. }
  57688. if (checkYaw || checkPitch) {
  57689. var spaceMat = BoneLookController._tmpMats[2];
  57690. var spaceMatInv = BoneLookController._tmpMats[3];
  57691. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  57692. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  57693. }
  57694. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  57695. spaceMat.copyFrom(mesh.getWorldMatrix());
  57696. }
  57697. else {
  57698. var forwardAxis = BoneLookController._tmpVecs[2];
  57699. forwardAxis.copyFrom(this._fowardAxis);
  57700. if (this._transformYawPitch) {
  57701. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  57702. }
  57703. if (parentBone) {
  57704. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  57705. }
  57706. else {
  57707. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  57708. }
  57709. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  57710. rightAxis.normalize();
  57711. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  57712. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  57713. }
  57714. spaceMat.invertToRef(spaceMatInv);
  57715. var xzlen;
  57716. if (checkPitch) {
  57717. var localTarget = BoneLookController._tmpVecs[3];
  57718. target.subtractToRef(bonePos, localTarget);
  57719. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57720. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57721. var pitch = Math.atan2(localTarget.y, xzlen);
  57722. var newPitch = pitch;
  57723. if (pitch > this._maxPitch) {
  57724. localTarget.y = this._maxPitchTan * xzlen;
  57725. newPitch = this._maxPitch;
  57726. }
  57727. else if (pitch < this._minPitch) {
  57728. localTarget.y = this._minPitchTan * xzlen;
  57729. newPitch = this._minPitch;
  57730. }
  57731. if (pitch != newPitch) {
  57732. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57733. localTarget.addInPlace(bonePos);
  57734. target = localTarget;
  57735. }
  57736. }
  57737. if (checkYaw) {
  57738. var localTarget = BoneLookController._tmpVecs[4];
  57739. target.subtractToRef(bonePos, localTarget);
  57740. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57741. var yaw = Math.atan2(localTarget.x, localTarget.z);
  57742. var newYaw = yaw;
  57743. if (yaw > this._maxYaw || yaw < this._minYaw) {
  57744. if (xzlen == null) {
  57745. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57746. }
  57747. if (this._yawRange > Math.PI) {
  57748. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  57749. localTarget.z = this._maxYawCos * xzlen;
  57750. localTarget.x = this._maxYawSin * xzlen;
  57751. newYaw = this._maxYaw;
  57752. }
  57753. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  57754. localTarget.z = this._minYawCos * xzlen;
  57755. localTarget.x = this._minYawSin * xzlen;
  57756. newYaw = this._minYaw;
  57757. }
  57758. }
  57759. else {
  57760. if (yaw > this._maxYaw) {
  57761. localTarget.z = this._maxYawCos * xzlen;
  57762. localTarget.x = this._maxYawSin * xzlen;
  57763. newYaw = this._maxYaw;
  57764. }
  57765. else if (yaw < this._minYaw) {
  57766. localTarget.z = this._minYawCos * xzlen;
  57767. localTarget.x = this._minYawSin * xzlen;
  57768. newYaw = this._minYaw;
  57769. }
  57770. }
  57771. }
  57772. if (this._slerping && this._yawRange > Math.PI) {
  57773. //are we going to be crossing into the min/max region?
  57774. var boneFwd = BoneLookController._tmpVecs[8];
  57775. boneFwd.copyFrom(BABYLON.Axis.Z);
  57776. if (this._transformYawPitch) {
  57777. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  57778. }
  57779. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  57780. this._boneQuat.toRotationMatrix(boneRotMat);
  57781. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  57782. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  57783. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  57784. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  57785. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  57786. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  57787. if (angBtwTar > angBtwMidYaw) {
  57788. if (xzlen == null) {
  57789. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57790. }
  57791. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  57792. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  57793. if (angBtwMin < angBtwMax) {
  57794. newYaw = boneYaw + Math.PI * .75;
  57795. localTarget.z = Math.cos(newYaw) * xzlen;
  57796. localTarget.x = Math.sin(newYaw) * xzlen;
  57797. }
  57798. else {
  57799. newYaw = boneYaw - Math.PI * .75;
  57800. localTarget.z = Math.cos(newYaw) * xzlen;
  57801. localTarget.x = Math.sin(newYaw) * xzlen;
  57802. }
  57803. }
  57804. }
  57805. if (yaw != newYaw) {
  57806. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57807. localTarget.addInPlace(bonePos);
  57808. target = localTarget;
  57809. }
  57810. }
  57811. }
  57812. var zaxis = BoneLookController._tmpVecs[5];
  57813. var xaxis = BoneLookController._tmpVecs[6];
  57814. var yaxis = BoneLookController._tmpVecs[7];
  57815. var _tmpQuat = BoneLookController._tmpQuat;
  57816. target.subtractToRef(bonePos, zaxis);
  57817. zaxis.normalize();
  57818. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  57819. xaxis.normalize();
  57820. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  57821. yaxis.normalize();
  57822. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  57823. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  57824. return;
  57825. }
  57826. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  57827. return;
  57828. }
  57829. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  57830. return;
  57831. }
  57832. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  57833. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  57834. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  57835. }
  57836. if (this.slerpAmount < 1) {
  57837. if (!this._slerping) {
  57838. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  57839. }
  57840. if (this._transformYawPitch) {
  57841. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  57842. }
  57843. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  57844. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  57845. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  57846. this._slerping = true;
  57847. }
  57848. else {
  57849. if (this._transformYawPitch) {
  57850. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  57851. }
  57852. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  57853. this._slerping = false;
  57854. }
  57855. };
  57856. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  57857. var angDiff = ang2 - ang1;
  57858. angDiff %= Math.PI * 2;
  57859. if (angDiff > Math.PI) {
  57860. angDiff -= Math.PI * 2;
  57861. }
  57862. else if (angDiff < -Math.PI) {
  57863. angDiff += Math.PI * 2;
  57864. }
  57865. return angDiff;
  57866. };
  57867. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  57868. ang1 %= (2 * Math.PI);
  57869. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  57870. ang2 %= (2 * Math.PI);
  57871. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  57872. var ab = 0;
  57873. if (ang1 < ang2) {
  57874. ab = ang2 - ang1;
  57875. }
  57876. else {
  57877. ab = ang1 - ang2;
  57878. }
  57879. if (ab > Math.PI) {
  57880. ab = Math.PI * 2 - ab;
  57881. }
  57882. return ab;
  57883. };
  57884. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  57885. ang %= (2 * Math.PI);
  57886. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  57887. ang1 %= (2 * Math.PI);
  57888. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  57889. ang2 %= (2 * Math.PI);
  57890. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  57891. if (ang1 < ang2) {
  57892. if (ang > ang1 && ang < ang2) {
  57893. return true;
  57894. }
  57895. }
  57896. else {
  57897. if (ang > ang2 && ang < ang1) {
  57898. return true;
  57899. }
  57900. }
  57901. return false;
  57902. };
  57903. 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()];
  57904. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  57905. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57906. return BoneLookController;
  57907. }());
  57908. BABYLON.BoneLookController = BoneLookController;
  57909. })(BABYLON || (BABYLON = {}));
  57910. //# sourceMappingURL=babylon.boneLookController.js.map
  57911. var BABYLON;
  57912. (function (BABYLON) {
  57913. var Skeleton = (function () {
  57914. function Skeleton(name, id, scene) {
  57915. this.name = name;
  57916. this.id = id;
  57917. this.bones = new Array();
  57918. this.needInitialSkinMatrix = false;
  57919. this._isDirty = true;
  57920. this._meshesWithPoseMatrix = new Array();
  57921. this._identity = BABYLON.Matrix.Identity();
  57922. this._ranges = {};
  57923. this._lastAbsoluteTransformsUpdateId = -1;
  57924. // Events
  57925. /**
  57926. * An event triggered before computing the skeleton's matrices
  57927. * @type {BABYLON.Observable}
  57928. */
  57929. this.onBeforeComputeObservable = new BABYLON.Observable();
  57930. this.bones = [];
  57931. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57932. scene.skeletons.push(this);
  57933. //make sure it will recalculate the matrix next time prepare is called.
  57934. this._isDirty = true;
  57935. }
  57936. // Members
  57937. Skeleton.prototype.getTransformMatrices = function (mesh) {
  57938. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  57939. return mesh._bonesTransformMatrices;
  57940. }
  57941. if (!this._transformMatrices) {
  57942. this.prepare();
  57943. }
  57944. return this._transformMatrices;
  57945. };
  57946. Skeleton.prototype.getScene = function () {
  57947. return this._scene;
  57948. };
  57949. // Methods
  57950. /**
  57951. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  57952. */
  57953. Skeleton.prototype.toString = function (fullDetails) {
  57954. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  57955. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  57956. if (fullDetails) {
  57957. ret += ", Ranges: {";
  57958. var first = true;
  57959. for (var name_1 in this._ranges) {
  57960. if (first) {
  57961. ret += ", ";
  57962. first = false;
  57963. }
  57964. ret += name_1;
  57965. }
  57966. ret += "}";
  57967. }
  57968. return ret;
  57969. };
  57970. /**
  57971. * Get bone's index searching by name
  57972. * @param {string} name is bone's name to search for
  57973. * @return {number} Indice of the bone. Returns -1 if not found
  57974. */
  57975. Skeleton.prototype.getBoneIndexByName = function (name) {
  57976. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  57977. if (this.bones[boneIndex].name === name) {
  57978. return boneIndex;
  57979. }
  57980. }
  57981. return -1;
  57982. };
  57983. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  57984. // check name not already in use
  57985. if (!this._ranges[name]) {
  57986. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  57987. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57988. if (this.bones[i].animations[0]) {
  57989. this.bones[i].animations[0].createRange(name, from, to);
  57990. }
  57991. }
  57992. }
  57993. };
  57994. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  57995. if (deleteFrames === void 0) { deleteFrames = true; }
  57996. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57997. if (this.bones[i].animations[0]) {
  57998. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  57999. }
  58000. }
  58001. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  58002. };
  58003. Skeleton.prototype.getAnimationRange = function (name) {
  58004. return this._ranges[name];
  58005. };
  58006. /**
  58007. * Returns as an Array, all AnimationRanges defined on this skeleton
  58008. */
  58009. Skeleton.prototype.getAnimationRanges = function () {
  58010. var animationRanges = [];
  58011. var name;
  58012. var i = 0;
  58013. for (name in this._ranges) {
  58014. animationRanges[i] = this._ranges[name];
  58015. i++;
  58016. }
  58017. return animationRanges;
  58018. };
  58019. /**
  58020. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  58021. */
  58022. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  58023. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58024. if (this._ranges[name] || !source.getAnimationRange(name)) {
  58025. return false;
  58026. }
  58027. var ret = true;
  58028. var frameOffset = this._getHighestAnimationFrame() + 1;
  58029. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  58030. var boneDict = {};
  58031. var sourceBones = source.bones;
  58032. var nBones;
  58033. var i;
  58034. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  58035. boneDict[sourceBones[i].name] = sourceBones[i];
  58036. }
  58037. if (this.bones.length !== sourceBones.length) {
  58038. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  58039. ret = false;
  58040. }
  58041. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  58042. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  58043. var boneName = this.bones[i].name;
  58044. var sourceBone = boneDict[boneName];
  58045. if (sourceBone) {
  58046. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  58047. }
  58048. else {
  58049. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  58050. ret = false;
  58051. }
  58052. }
  58053. // do not call createAnimationRange(), since it also is done to bones, which was already done
  58054. var range = source.getAnimationRange(name);
  58055. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  58056. return ret;
  58057. };
  58058. Skeleton.prototype.returnToRest = function () {
  58059. for (var index = 0; index < this.bones.length; index++) {
  58060. this.bones[index].returnToRest();
  58061. }
  58062. };
  58063. Skeleton.prototype._getHighestAnimationFrame = function () {
  58064. var ret = 0;
  58065. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58066. if (this.bones[i].animations[0]) {
  58067. var highest = this.bones[i].animations[0].getHighestFrame();
  58068. if (ret < highest) {
  58069. ret = highest;
  58070. }
  58071. }
  58072. }
  58073. return ret;
  58074. };
  58075. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  58076. var range = this.getAnimationRange(name);
  58077. if (!range) {
  58078. return null;
  58079. }
  58080. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  58081. };
  58082. Skeleton.prototype._markAsDirty = function () {
  58083. this._isDirty = true;
  58084. };
  58085. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  58086. this._meshesWithPoseMatrix.push(mesh);
  58087. };
  58088. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  58089. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  58090. if (index > -1) {
  58091. this._meshesWithPoseMatrix.splice(index, 1);
  58092. }
  58093. };
  58094. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  58095. this.onBeforeComputeObservable.notifyObservers(this);
  58096. for (var index = 0; index < this.bones.length; index++) {
  58097. var bone = this.bones[index];
  58098. var parentBone = bone.getParent();
  58099. if (parentBone) {
  58100. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  58101. }
  58102. else {
  58103. if (initialSkinMatrix) {
  58104. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  58105. }
  58106. else {
  58107. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  58108. }
  58109. }
  58110. if (bone._index !== -1) {
  58111. var mappedIndex = bone._index === undefined ? index : bone._index;
  58112. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  58113. }
  58114. }
  58115. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  58116. };
  58117. Skeleton.prototype.prepare = function () {
  58118. if (!this._isDirty) {
  58119. return;
  58120. }
  58121. if (this.needInitialSkinMatrix) {
  58122. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  58123. var mesh = this._meshesWithPoseMatrix[index];
  58124. var poseMatrix = mesh.getPoseMatrix();
  58125. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  58126. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58127. }
  58128. if (this._synchronizedWithMesh !== mesh) {
  58129. this._synchronizedWithMesh = mesh;
  58130. // Prepare bones
  58131. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  58132. var bone = this.bones[boneIndex];
  58133. if (!bone.getParent()) {
  58134. var matrix = bone.getBaseMatrix();
  58135. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  58136. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  58137. }
  58138. }
  58139. }
  58140. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  58141. }
  58142. }
  58143. else {
  58144. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  58145. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58146. }
  58147. this._computeTransformMatrices(this._transformMatrices, null);
  58148. }
  58149. this._isDirty = false;
  58150. this._scene._activeBones.addCount(this.bones.length, false);
  58151. };
  58152. Skeleton.prototype.getAnimatables = function () {
  58153. if (!this._animatables || this._animatables.length !== this.bones.length) {
  58154. this._animatables = [];
  58155. for (var index = 0; index < this.bones.length; index++) {
  58156. this._animatables.push(this.bones[index]);
  58157. }
  58158. }
  58159. return this._animatables;
  58160. };
  58161. Skeleton.prototype.clone = function (name, id) {
  58162. var result = new Skeleton(name, id || name, this._scene);
  58163. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58164. for (var index = 0; index < this.bones.length; index++) {
  58165. var source = this.bones[index];
  58166. var parentBone = null;
  58167. if (source.getParent()) {
  58168. var parentIndex = this.bones.indexOf(source.getParent());
  58169. parentBone = result.bones[parentIndex];
  58170. }
  58171. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  58172. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  58173. }
  58174. if (this._ranges) {
  58175. result._ranges = {};
  58176. for (var rangeName in this._ranges) {
  58177. result._ranges[rangeName] = this._ranges[rangeName].clone();
  58178. }
  58179. }
  58180. this._isDirty = true;
  58181. return result;
  58182. };
  58183. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  58184. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  58185. this.bones.forEach(function (bone) {
  58186. bone.animations.forEach(function (animation) {
  58187. animation.enableBlending = true;
  58188. animation.blendingSpeed = blendingSpeed;
  58189. });
  58190. });
  58191. };
  58192. Skeleton.prototype.dispose = function () {
  58193. this._meshesWithPoseMatrix = [];
  58194. // Animations
  58195. this.getScene().stopAnimation(this);
  58196. // Remove from scene
  58197. this.getScene().removeSkeleton(this);
  58198. };
  58199. Skeleton.prototype.serialize = function () {
  58200. var serializationObject = {};
  58201. serializationObject.name = this.name;
  58202. serializationObject.id = this.id;
  58203. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  58204. serializationObject.bones = [];
  58205. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58206. for (var index = 0; index < this.bones.length; index++) {
  58207. var bone = this.bones[index];
  58208. var serializedBone = {
  58209. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  58210. name: bone.name,
  58211. matrix: bone.getBaseMatrix().toArray(),
  58212. rest: bone.getRestPose().toArray()
  58213. };
  58214. serializationObject.bones.push(serializedBone);
  58215. if (bone.length) {
  58216. serializedBone.length = bone.length;
  58217. }
  58218. if (bone.animations && bone.animations.length > 0) {
  58219. serializedBone.animation = bone.animations[0].serialize();
  58220. }
  58221. serializationObject.ranges = [];
  58222. for (var name in this._ranges) {
  58223. var range = {};
  58224. range.name = name;
  58225. range.from = this._ranges[name].from;
  58226. range.to = this._ranges[name].to;
  58227. serializationObject.ranges.push(range);
  58228. }
  58229. }
  58230. return serializationObject;
  58231. };
  58232. Skeleton.Parse = function (parsedSkeleton, scene) {
  58233. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  58234. if (parsedSkeleton.dimensionsAtRest) {
  58235. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  58236. }
  58237. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  58238. var index;
  58239. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  58240. var parsedBone = parsedSkeleton.bones[index];
  58241. var parentBone = null;
  58242. if (parsedBone.parentBoneIndex > -1) {
  58243. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  58244. }
  58245. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  58246. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  58247. if (parsedBone.length) {
  58248. bone.length = parsedBone.length;
  58249. }
  58250. if (parsedBone.animation) {
  58251. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  58252. }
  58253. }
  58254. // placed after bones, so createAnimationRange can cascade down
  58255. if (parsedSkeleton.ranges) {
  58256. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  58257. var data = parsedSkeleton.ranges[index];
  58258. skeleton.createAnimationRange(data.name, data.from, data.to);
  58259. }
  58260. }
  58261. return skeleton;
  58262. };
  58263. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  58264. if (forceUpdate === void 0) { forceUpdate = false; }
  58265. var renderId = this._scene.getRenderId();
  58266. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  58267. this.bones[0].computeAbsoluteTransforms();
  58268. this._lastAbsoluteTransformsUpdateId = renderId;
  58269. }
  58270. };
  58271. Skeleton.prototype.getPoseMatrix = function () {
  58272. var poseMatrix;
  58273. if (this._meshesWithPoseMatrix.length > 0) {
  58274. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  58275. }
  58276. return poseMatrix;
  58277. };
  58278. Skeleton.prototype.sortBones = function () {
  58279. var bones = new Array();
  58280. var visited = new Array(this.bones.length);
  58281. for (var index = 0; index < this.bones.length; index++) {
  58282. this._sortBones(index, bones, visited);
  58283. }
  58284. this.bones = bones;
  58285. };
  58286. Skeleton.prototype._sortBones = function (index, bones, visited) {
  58287. if (visited[index]) {
  58288. return;
  58289. }
  58290. visited[index] = true;
  58291. var bone = this.bones[index];
  58292. if (bone._index === undefined) {
  58293. bone._index = index;
  58294. }
  58295. var parentBone = bone.getParent();
  58296. if (parentBone) {
  58297. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  58298. }
  58299. bones.push(bone);
  58300. };
  58301. return Skeleton;
  58302. }());
  58303. BABYLON.Skeleton = Skeleton;
  58304. })(BABYLON || (BABYLON = {}));
  58305. //# sourceMappingURL=babylon.skeleton.js.map
  58306. var BABYLON;
  58307. (function (BABYLON) {
  58308. var SphericalPolynomial = (function () {
  58309. function SphericalPolynomial() {
  58310. this.x = BABYLON.Vector3.Zero();
  58311. this.y = BABYLON.Vector3.Zero();
  58312. this.z = BABYLON.Vector3.Zero();
  58313. this.xx = BABYLON.Vector3.Zero();
  58314. this.yy = BABYLON.Vector3.Zero();
  58315. this.zz = BABYLON.Vector3.Zero();
  58316. this.xy = BABYLON.Vector3.Zero();
  58317. this.yz = BABYLON.Vector3.Zero();
  58318. this.zx = BABYLON.Vector3.Zero();
  58319. }
  58320. SphericalPolynomial.prototype.addAmbient = function (color) {
  58321. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58322. this.xx = this.xx.add(colorVector);
  58323. this.yy = this.yy.add(colorVector);
  58324. this.zz = this.zz.add(colorVector);
  58325. };
  58326. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  58327. var result = new SphericalPolynomial();
  58328. result.x = harmonics.L11.scale(1.02333);
  58329. result.y = harmonics.L1_1.scale(1.02333);
  58330. result.z = harmonics.L10.scale(1.02333);
  58331. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  58332. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  58333. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  58334. result.yz = harmonics.L2_1.scale(0.858086);
  58335. result.zx = harmonics.L21.scale(0.858086);
  58336. result.xy = harmonics.L2_2.scale(0.858086);
  58337. result.scale(1.0 / Math.PI);
  58338. return result;
  58339. };
  58340. SphericalPolynomial.prototype.scale = function (scale) {
  58341. this.x = this.x.scale(scale);
  58342. this.y = this.y.scale(scale);
  58343. this.z = this.z.scale(scale);
  58344. this.xx = this.xx.scale(scale);
  58345. this.yy = this.yy.scale(scale);
  58346. this.zz = this.zz.scale(scale);
  58347. this.yz = this.yz.scale(scale);
  58348. this.zx = this.zx.scale(scale);
  58349. this.xy = this.xy.scale(scale);
  58350. };
  58351. return SphericalPolynomial;
  58352. }());
  58353. BABYLON.SphericalPolynomial = SphericalPolynomial;
  58354. var SphericalHarmonics = (function () {
  58355. function SphericalHarmonics() {
  58356. this.L00 = BABYLON.Vector3.Zero();
  58357. this.L1_1 = BABYLON.Vector3.Zero();
  58358. this.L10 = BABYLON.Vector3.Zero();
  58359. this.L11 = BABYLON.Vector3.Zero();
  58360. this.L2_2 = BABYLON.Vector3.Zero();
  58361. this.L2_1 = BABYLON.Vector3.Zero();
  58362. this.L20 = BABYLON.Vector3.Zero();
  58363. this.L21 = BABYLON.Vector3.Zero();
  58364. this.L22 = BABYLON.Vector3.Zero();
  58365. }
  58366. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  58367. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58368. var c = colorVector.scale(deltaSolidAngle);
  58369. this.L00 = this.L00.add(c.scale(0.282095));
  58370. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  58371. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  58372. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  58373. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  58374. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  58375. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  58376. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  58377. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  58378. };
  58379. SphericalHarmonics.prototype.scale = function (scale) {
  58380. this.L00 = this.L00.scale(scale);
  58381. this.L1_1 = this.L1_1.scale(scale);
  58382. this.L10 = this.L10.scale(scale);
  58383. this.L11 = this.L11.scale(scale);
  58384. this.L2_2 = this.L2_2.scale(scale);
  58385. this.L2_1 = this.L2_1.scale(scale);
  58386. this.L20 = this.L20.scale(scale);
  58387. this.L21 = this.L21.scale(scale);
  58388. this.L22 = this.L22.scale(scale);
  58389. };
  58390. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  58391. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  58392. //
  58393. // E_lm = A_l * L_lm
  58394. //
  58395. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  58396. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  58397. // the scaling factors are given in equation 9.
  58398. // Constant (Band 0)
  58399. this.L00 = this.L00.scale(3.141593);
  58400. // Linear (Band 1)
  58401. this.L1_1 = this.L1_1.scale(2.094395);
  58402. this.L10 = this.L10.scale(2.094395);
  58403. this.L11 = this.L11.scale(2.094395);
  58404. // Quadratic (Band 2)
  58405. this.L2_2 = this.L2_2.scale(0.785398);
  58406. this.L2_1 = this.L2_1.scale(0.785398);
  58407. this.L20 = this.L20.scale(0.785398);
  58408. this.L21 = this.L21.scale(0.785398);
  58409. this.L22 = this.L22.scale(0.785398);
  58410. };
  58411. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  58412. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  58413. // L = (1/pi) * E * rho
  58414. //
  58415. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  58416. this.scale(1.0 / Math.PI);
  58417. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  58418. // (The pixel shader must apply albedo after texture fetches, etc).
  58419. };
  58420. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  58421. var result = new SphericalHarmonics();
  58422. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  58423. result.L1_1 = polynomial.y.scale(0.977204);
  58424. result.L10 = polynomial.z.scale(0.977204);
  58425. result.L11 = polynomial.x.scale(0.977204);
  58426. result.L2_2 = polynomial.xy.scale(1.16538);
  58427. result.L2_1 = polynomial.yz.scale(1.16538);
  58428. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  58429. result.L21 = polynomial.zx.scale(1.16538);
  58430. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  58431. result.scale(Math.PI);
  58432. return result;
  58433. };
  58434. return SphericalHarmonics;
  58435. }());
  58436. BABYLON.SphericalHarmonics = SphericalHarmonics;
  58437. })(BABYLON || (BABYLON = {}));
  58438. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  58439. var BABYLON;
  58440. (function (BABYLON) {
  58441. var Internals;
  58442. (function (Internals) {
  58443. var FileFaceOrientation = (function () {
  58444. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58445. this.name = name;
  58446. this.worldAxisForNormal = worldAxisForNormal;
  58447. this.worldAxisForFileX = worldAxisForFileX;
  58448. this.worldAxisForFileY = worldAxisForFileY;
  58449. }
  58450. return FileFaceOrientation;
  58451. }());
  58452. ;
  58453. /**
  58454. * Helper class dealing with the extraction of spherical polynomial dataArray
  58455. * from a cube map.
  58456. */
  58457. var CubeMapToSphericalPolynomialTools = (function () {
  58458. function CubeMapToSphericalPolynomialTools() {
  58459. }
  58460. /**
  58461. * Converts a texture to the according Spherical Polynomial data.
  58462. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58463. *
  58464. * @param texture The texture to extract the information from.
  58465. * @return The Spherical Polynomial data.
  58466. */
  58467. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  58468. if (!texture.isCube) {
  58469. // Only supports cube Textures currently.
  58470. return null;
  58471. }
  58472. var size = texture.getSize().width;
  58473. var right = texture.readPixels(0);
  58474. var left = texture.readPixels(1);
  58475. var up;
  58476. var down;
  58477. if (texture.isRenderTarget) {
  58478. up = texture.readPixels(3);
  58479. down = texture.readPixels(2);
  58480. }
  58481. else {
  58482. up = texture.readPixels(2);
  58483. down = texture.readPixels(3);
  58484. }
  58485. var front = texture.readPixels(4);
  58486. var back = texture.readPixels(5);
  58487. var gammaSpace = texture.gammaSpace;
  58488. // Always read as RGBA.
  58489. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  58490. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58491. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58492. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58493. }
  58494. var cubeInfo = {
  58495. size: size,
  58496. right: right,
  58497. left: left,
  58498. up: up,
  58499. down: down,
  58500. front: front,
  58501. back: back,
  58502. format: format,
  58503. type: type,
  58504. gammaSpace: gammaSpace,
  58505. };
  58506. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  58507. };
  58508. /**
  58509. * Converts a cubemap to the according Spherical Polynomial data.
  58510. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58511. *
  58512. * @param cubeInfo The Cube map to extract the information from.
  58513. * @return The Spherical Polynomial data.
  58514. */
  58515. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58516. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58517. var totalSolidAngle = 0.0;
  58518. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58519. var du = 2.0 / cubeInfo.size;
  58520. var dv = du;
  58521. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58522. var minUV = du * 0.5 - 1.0;
  58523. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58524. var fileFace = this.FileFaces[faceIndex];
  58525. var dataArray = cubeInfo[fileFace.name];
  58526. var v = minUV;
  58527. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58528. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58529. // Because SP is still linear, so summation is fine in that basis.
  58530. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  58531. for (var y = 0; y < cubeInfo.size; y++) {
  58532. var u = minUV;
  58533. for (var x = 0; x < cubeInfo.size; x++) {
  58534. // World direction (not normalised)
  58535. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58536. worldDirection.normalize();
  58537. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58538. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  58539. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  58540. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  58541. // Handle Integer types.
  58542. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58543. r /= 255;
  58544. g /= 255;
  58545. b /= 255;
  58546. }
  58547. // Handle Gamma space textures.
  58548. if (cubeInfo.gammaSpace) {
  58549. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  58550. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  58551. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  58552. }
  58553. var color = new BABYLON.Color3(r, g, b);
  58554. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58555. totalSolidAngle += deltaSolidAngle;
  58556. u += du;
  58557. }
  58558. v += dv;
  58559. }
  58560. }
  58561. // Solid angle for entire sphere is 4*pi
  58562. var sphereSolidAngle = 4.0 * Math.PI;
  58563. // Adjust the solid angle to allow for how many faces we processed.
  58564. var facesProcessed = 6.0;
  58565. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  58566. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  58567. // This is needed because the numerical integration over the cube uses a
  58568. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  58569. // and also to compensate for accumulative error due to float precision in the summation.
  58570. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  58571. sphericalHarmonics.scale(correctionFactor);
  58572. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  58573. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  58574. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58575. };
  58576. CubeMapToSphericalPolynomialTools.FileFaces = [
  58577. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58578. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58579. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58580. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58581. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58582. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58583. ];
  58584. return CubeMapToSphericalPolynomialTools;
  58585. }());
  58586. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58587. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58588. })(BABYLON || (BABYLON = {}));
  58589. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  58590. var BABYLON;
  58591. (function (BABYLON) {
  58592. var Internals;
  58593. (function (Internals) {
  58594. /**
  58595. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58596. */
  58597. var PanoramaToCubeMapTools = (function () {
  58598. function PanoramaToCubeMapTools() {
  58599. }
  58600. /**
  58601. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58602. *
  58603. * @param float32Array The source data.
  58604. * @param inputWidth The width of the input panorama.
  58605. * @param inputhHeight The height of the input panorama.
  58606. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58607. * @return The cubemap data
  58608. */
  58609. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58610. if (!float32Array) {
  58611. throw "ConvertPanoramaToCubemap: input cannot be null";
  58612. }
  58613. if (float32Array.length != inputWidth * inputHeight * 3) {
  58614. throw "ConvertPanoramaToCubemap: input size is wrong";
  58615. }
  58616. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58617. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58618. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58619. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58620. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58621. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58622. return {
  58623. front: textureFront,
  58624. back: textureBack,
  58625. left: textureLeft,
  58626. right: textureRight,
  58627. up: textureUp,
  58628. down: textureDown,
  58629. size: size,
  58630. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  58631. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  58632. gammaSpace: false,
  58633. };
  58634. };
  58635. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58636. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58637. var textureArray = new Float32Array(buffer);
  58638. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58639. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58640. var dy = 1 / texSize;
  58641. var fy = 0;
  58642. for (var y = 0; y < texSize; y++) {
  58643. var xv1 = faceData[0];
  58644. var xv2 = faceData[2];
  58645. for (var x = 0; x < texSize; x++) {
  58646. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58647. v.normalize();
  58648. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58649. // 3 channels per pixels
  58650. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58651. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58652. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58653. xv1 = xv1.add(rotDX1);
  58654. xv2 = xv2.add(rotDX2);
  58655. }
  58656. fy += dy;
  58657. }
  58658. return textureArray;
  58659. };
  58660. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58661. var theta = Math.atan2(vDir.z, vDir.x);
  58662. var phi = Math.acos(vDir.y);
  58663. while (theta < -Math.PI)
  58664. theta += 2 * Math.PI;
  58665. while (theta > Math.PI)
  58666. theta -= 2 * Math.PI;
  58667. var dx = theta / Math.PI;
  58668. var dy = phi / Math.PI;
  58669. // recenter.
  58670. dx = dx * 0.5 + 0.5;
  58671. var px = Math.round(dx * inputWidth);
  58672. if (px < 0)
  58673. px = 0;
  58674. else if (px >= inputWidth)
  58675. px = inputWidth - 1;
  58676. var py = Math.round(dy * inputHeight);
  58677. if (py < 0)
  58678. py = 0;
  58679. else if (py >= inputHeight)
  58680. py = inputHeight - 1;
  58681. var inputY = (inputHeight - py - 1);
  58682. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58683. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58684. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58685. return {
  58686. r: r,
  58687. g: g,
  58688. b: b
  58689. };
  58690. };
  58691. PanoramaToCubeMapTools.FACE_FRONT = [
  58692. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58693. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58694. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58695. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58696. ];
  58697. PanoramaToCubeMapTools.FACE_BACK = [
  58698. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58699. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58700. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58701. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58702. ];
  58703. PanoramaToCubeMapTools.FACE_RIGHT = [
  58704. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58705. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58706. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58707. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58708. ];
  58709. PanoramaToCubeMapTools.FACE_LEFT = [
  58710. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58711. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58712. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58713. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58714. ];
  58715. PanoramaToCubeMapTools.FACE_DOWN = [
  58716. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58717. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58718. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58719. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58720. ];
  58721. PanoramaToCubeMapTools.FACE_UP = [
  58722. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58723. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58724. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58725. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58726. ];
  58727. return PanoramaToCubeMapTools;
  58728. }());
  58729. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58730. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58731. })(BABYLON || (BABYLON = {}));
  58732. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  58733. var BABYLON;
  58734. (function (BABYLON) {
  58735. var Internals;
  58736. (function (Internals) {
  58737. ;
  58738. /**
  58739. * This groups tools to convert HDR texture to native colors array.
  58740. */
  58741. var HDRTools = (function () {
  58742. function HDRTools() {
  58743. }
  58744. HDRTools.Ldexp = function (mantissa, exponent) {
  58745. if (exponent > 1023) {
  58746. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58747. }
  58748. if (exponent < -1074) {
  58749. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58750. }
  58751. return mantissa * Math.pow(2, exponent);
  58752. };
  58753. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58754. if (exponent > 0) {
  58755. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58756. float32array[index + 0] = red * exponent;
  58757. float32array[index + 1] = green * exponent;
  58758. float32array[index + 2] = blue * exponent;
  58759. }
  58760. else {
  58761. float32array[index + 0] = 0;
  58762. float32array[index + 1] = 0;
  58763. float32array[index + 2] = 0;
  58764. }
  58765. };
  58766. HDRTools.readStringLine = function (uint8array, startIndex) {
  58767. var line = "";
  58768. var character = "";
  58769. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58770. character = String.fromCharCode(uint8array[i]);
  58771. if (character == "\n") {
  58772. break;
  58773. }
  58774. line += character;
  58775. }
  58776. return line;
  58777. };
  58778. /**
  58779. * Reads header information from an RGBE texture stored in a native array.
  58780. * More information on this format are available here:
  58781. * https://en.wikipedia.org/wiki/RGBE_image_format
  58782. *
  58783. * @param uint8array The binary file stored in native array.
  58784. * @return The header information.
  58785. */
  58786. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58787. var height = 0;
  58788. var width = 0;
  58789. var line = this.readStringLine(uint8array, 0);
  58790. if (line[0] != '#' || line[1] != '?') {
  58791. throw "Bad HDR Format.";
  58792. }
  58793. var endOfHeader = false;
  58794. var findFormat = false;
  58795. var lineIndex = 0;
  58796. do {
  58797. lineIndex += (line.length + 1);
  58798. line = this.readStringLine(uint8array, lineIndex);
  58799. if (line == "FORMAT=32-bit_rle_rgbe") {
  58800. findFormat = true;
  58801. }
  58802. else if (line.length == 0) {
  58803. endOfHeader = true;
  58804. }
  58805. } while (!endOfHeader);
  58806. if (!findFormat) {
  58807. throw "HDR Bad header format, unsupported FORMAT";
  58808. }
  58809. lineIndex += (line.length + 1);
  58810. line = this.readStringLine(uint8array, lineIndex);
  58811. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58812. var match = sizeRegexp.exec(line);
  58813. // TODO. Support +Y and -X if needed.
  58814. if (match.length < 3) {
  58815. throw "HDR Bad header format, no size";
  58816. }
  58817. width = parseInt(match[2]);
  58818. height = parseInt(match[1]);
  58819. if (width < 8 || width > 0x7fff) {
  58820. throw "HDR Bad header format, unsupported size";
  58821. }
  58822. lineIndex += (line.length + 1);
  58823. return {
  58824. height: height,
  58825. width: width,
  58826. dataPosition: lineIndex
  58827. };
  58828. };
  58829. /**
  58830. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58831. * This RGBE texture needs to store the information as a panorama.
  58832. *
  58833. * More information on this format are available here:
  58834. * https://en.wikipedia.org/wiki/RGBE_image_format
  58835. *
  58836. * @param buffer The binary file stored in an array buffer.
  58837. * @param size The expected size of the extracted cubemap.
  58838. * @return The Cube Map information.
  58839. */
  58840. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58841. var uint8array = new Uint8Array(buffer);
  58842. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58843. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58844. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58845. return cubeMapData;
  58846. };
  58847. /**
  58848. * Returns the pixels data extracted from an RGBE texture.
  58849. * This pixels will be stored left to right up to down in the R G B order in one array.
  58850. *
  58851. * More information on this format are available here:
  58852. * https://en.wikipedia.org/wiki/RGBE_image_format
  58853. *
  58854. * @param uint8array The binary file stored in an array buffer.
  58855. * @param hdrInfo The header information of the file.
  58856. * @return The pixels data in RGB right to left up to down order.
  58857. */
  58858. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58859. // Keep for multi format supports.
  58860. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58861. };
  58862. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58863. var num_scanlines = hdrInfo.height;
  58864. var scanline_width = hdrInfo.width;
  58865. var a, b, c, d, count;
  58866. var dataIndex = hdrInfo.dataPosition;
  58867. var index = 0, endIndex = 0, i = 0;
  58868. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58869. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58870. // 3 channels of 4 bytes per pixel in float.
  58871. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58872. var resultArray = new Float32Array(resultBuffer);
  58873. // read in each successive scanline
  58874. while (num_scanlines > 0) {
  58875. a = uint8array[dataIndex++];
  58876. b = uint8array[dataIndex++];
  58877. c = uint8array[dataIndex++];
  58878. d = uint8array[dataIndex++];
  58879. if (a != 2 || b != 2 || (c & 0x80)) {
  58880. // this file is not run length encoded
  58881. throw "HDR Bad header format, not RLE";
  58882. }
  58883. if (((c << 8) | d) != scanline_width) {
  58884. throw "HDR Bad header format, wrong scan line width";
  58885. }
  58886. index = 0;
  58887. // read each of the four channels for the scanline into the buffer
  58888. for (i = 0; i < 4; i++) {
  58889. endIndex = (i + 1) * scanline_width;
  58890. while (index < endIndex) {
  58891. a = uint8array[dataIndex++];
  58892. b = uint8array[dataIndex++];
  58893. if (a > 128) {
  58894. // a run of the same value
  58895. count = a - 128;
  58896. if ((count == 0) || (count > endIndex - index)) {
  58897. throw "HDR Bad Format, bad scanline data (run)";
  58898. }
  58899. while (count-- > 0) {
  58900. scanLineArray[index++] = b;
  58901. }
  58902. }
  58903. else {
  58904. // a non-run
  58905. count = a;
  58906. if ((count == 0) || (count > endIndex - index)) {
  58907. throw "HDR Bad Format, bad scanline data (non-run)";
  58908. }
  58909. scanLineArray[index++] = b;
  58910. if (--count > 0) {
  58911. for (var j = 0; j < count; j++) {
  58912. scanLineArray[index++] = uint8array[dataIndex++];
  58913. }
  58914. }
  58915. }
  58916. }
  58917. }
  58918. // now convert data from buffer into floats
  58919. for (i = 0; i < scanline_width; i++) {
  58920. a = scanLineArray[i];
  58921. b = scanLineArray[i + scanline_width];
  58922. c = scanLineArray[i + 2 * scanline_width];
  58923. d = scanLineArray[i + 3 * scanline_width];
  58924. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58925. }
  58926. num_scanlines--;
  58927. }
  58928. return resultArray;
  58929. };
  58930. return HDRTools;
  58931. }());
  58932. Internals.HDRTools = HDRTools;
  58933. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58934. })(BABYLON || (BABYLON = {}));
  58935. //# sourceMappingURL=babylon.hdr.js.map
  58936. var BABYLON;
  58937. (function (BABYLON) {
  58938. /**
  58939. * This represents a texture coming from an HDR input.
  58940. *
  58941. * The only supported format is currently panorama picture stored in RGBE format.
  58942. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58943. */
  58944. var HDRCubeTexture = (function (_super) {
  58945. __extends(HDRCubeTexture, _super);
  58946. /**
  58947. * Instantiates an HDRTexture from the following parameters.
  58948. *
  58949. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58950. * @param scene The scene the texture will be used in
  58951. * @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.
  58952. * @param noMipmap Forces to not generate the mipmap if true
  58953. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58954. * @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)
  58955. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58956. */
  58957. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  58958. if (noMipmap === void 0) { noMipmap = false; }
  58959. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58960. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58961. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58962. if (onLoad === void 0) { onLoad = null; }
  58963. if (onError === void 0) { onError = null; }
  58964. var _this = _super.call(this, scene) || this;
  58965. _this._useInGammaSpace = false;
  58966. _this._generateHarmonics = true;
  58967. _this._isBABYLONPreprocessed = false;
  58968. _this._onLoad = null;
  58969. _this._onError = null;
  58970. /**
  58971. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58972. */
  58973. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58974. /**
  58975. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58976. * This is usefull at run time to apply the good shader.
  58977. */
  58978. _this.isPMREM = false;
  58979. _this._isBlocking = true;
  58980. if (!url) {
  58981. return _this;
  58982. }
  58983. _this.name = url;
  58984. _this.url = url;
  58985. _this.hasAlpha = false;
  58986. _this.isCube = true;
  58987. _this._textureMatrix = BABYLON.Matrix.Identity();
  58988. _this._onLoad = onLoad;
  58989. _this._onError = onError;
  58990. _this.gammaSpace = false;
  58991. if (size) {
  58992. _this._isBABYLONPreprocessed = false;
  58993. _this._noMipmap = noMipmap;
  58994. _this._size = size;
  58995. _this._useInGammaSpace = useInGammaSpace;
  58996. _this._usePMREMGenerator = usePMREMGenerator &&
  58997. scene.getEngine().getCaps().textureLOD &&
  58998. _this.getScene().getEngine().getCaps().textureFloat &&
  58999. !_this._useInGammaSpace;
  59000. }
  59001. else {
  59002. _this._isBABYLONPreprocessed = true;
  59003. _this._noMipmap = false;
  59004. _this._useInGammaSpace = false;
  59005. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59006. _this.getScene().getEngine().getCaps().textureFloat &&
  59007. !_this._useInGammaSpace;
  59008. }
  59009. _this.isPMREM = _this._usePMREMGenerator;
  59010. _this._texture = _this._getFromCache(url, _this._noMipmap);
  59011. if (!_this._texture) {
  59012. if (!scene.useDelayedTextureLoading) {
  59013. _this.loadTexture();
  59014. }
  59015. else {
  59016. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59017. }
  59018. }
  59019. return _this;
  59020. }
  59021. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  59022. /**
  59023. * Gets wether or not the texture is blocking during loading.
  59024. */
  59025. get: function () {
  59026. return this._isBlocking;
  59027. },
  59028. /**
  59029. * Sets wether or not the texture is blocking during loading.
  59030. */
  59031. set: function (value) {
  59032. this._isBlocking = value;
  59033. },
  59034. enumerable: true,
  59035. configurable: true
  59036. });
  59037. /**
  59038. * Occurs when the file is a preprocessed .babylon.hdr file.
  59039. */
  59040. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59041. var _this = this;
  59042. var mipLevels = 0;
  59043. var floatArrayView = null;
  59044. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59045. var mips = [];
  59046. var startIndex = 30;
  59047. for (var level = 0; level < mipLevels; level++) {
  59048. mips.push([]);
  59049. // Fill each pixel of the mip level.
  59050. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59051. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59052. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59053. mips[level].push(faceData);
  59054. startIndex += faceSize;
  59055. }
  59056. }
  59057. return mips;
  59058. } : null;
  59059. var callback = function (buffer) {
  59060. // Create Native Array Views
  59061. var intArrayView = new Int32Array(buffer);
  59062. floatArrayView = new Float32Array(buffer);
  59063. // Fill header.
  59064. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59065. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59066. // Update Texture Information.
  59067. _this._texture.updateSize(_this._size, _this._size);
  59068. // Fill polynomial information.
  59069. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59070. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59071. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59072. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59073. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59074. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59075. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59076. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59077. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59078. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59079. _this.sphericalPolynomial = sphericalPolynomial;
  59080. // Fill pixel data.
  59081. mipLevels = intArrayView[29]; // Number of mip levels.
  59082. var startIndex = 30;
  59083. var data = [];
  59084. var faceSize = Math.pow(_this._size, 2) * 3;
  59085. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59086. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59087. startIndex += faceSize;
  59088. }
  59089. var results = [];
  59090. var byteArray = null;
  59091. // Push each faces.
  59092. for (var k = 0; k < 6; k++) {
  59093. var dataFace = null;
  59094. // To be deprecated.
  59095. if (version === 1) {
  59096. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  59097. dataFace = data[j];
  59098. }
  59099. // If special cases.
  59100. if (!mipmapGenerator) {
  59101. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59102. // 3 channels of 1 bytes per pixel in bytes.
  59103. var byteBuffer = new ArrayBuffer(faceSize);
  59104. byteArray = new Uint8Array(byteBuffer);
  59105. }
  59106. for (var i = 0; i < _this._size * _this._size; i++) {
  59107. // Put in gamma space if requested.
  59108. if (_this._useInGammaSpace) {
  59109. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59110. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59111. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59112. }
  59113. // Convert to int texture for fallback.
  59114. if (byteArray) {
  59115. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59116. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59117. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59118. // May use luminance instead if the result is not accurate.
  59119. var max = Math.max(Math.max(r, g), b);
  59120. if (max > 255) {
  59121. var scale = 255 / max;
  59122. r *= scale;
  59123. g *= scale;
  59124. b *= scale;
  59125. }
  59126. byteArray[(i * 3) + 0] = r;
  59127. byteArray[(i * 3) + 1] = g;
  59128. byteArray[(i * 3) + 2] = b;
  59129. }
  59130. }
  59131. }
  59132. // Fill the array accordingly.
  59133. if (byteArray) {
  59134. results.push(byteArray);
  59135. }
  59136. else {
  59137. results.push(dataFace);
  59138. }
  59139. }
  59140. return results;
  59141. };
  59142. 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);
  59143. };
  59144. /**
  59145. * Occurs when the file is raw .hdr file.
  59146. */
  59147. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59148. var _this = this;
  59149. var callback = function (buffer) {
  59150. // Extract the raw linear data.
  59151. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59152. // Generate harmonics if needed.
  59153. if (_this._generateHarmonics) {
  59154. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59155. _this.sphericalPolynomial = sphericalPolynomial;
  59156. }
  59157. var results = [];
  59158. var byteArray = null;
  59159. // Push each faces.
  59160. for (var j = 0; j < 6; j++) {
  59161. // Create uintarray fallback.
  59162. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59163. // 3 channels of 1 bytes per pixel in bytes.
  59164. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59165. byteArray = new Uint8Array(byteBuffer);
  59166. }
  59167. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59168. // If special cases.
  59169. if (_this._useInGammaSpace || byteArray) {
  59170. for (var i = 0; i < _this._size * _this._size; i++) {
  59171. // Put in gamma space if requested.
  59172. if (_this._useInGammaSpace) {
  59173. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59174. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59175. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59176. }
  59177. // Convert to int texture for fallback.
  59178. if (byteArray) {
  59179. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59180. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59181. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59182. // May use luminance instead if the result is not accurate.
  59183. var max = Math.max(Math.max(r, g), b);
  59184. if (max > 255) {
  59185. var scale = 255 / max;
  59186. r *= scale;
  59187. g *= scale;
  59188. b *= scale;
  59189. }
  59190. byteArray[(i * 3) + 0] = r;
  59191. byteArray[(i * 3) + 1] = g;
  59192. byteArray[(i * 3) + 2] = b;
  59193. }
  59194. }
  59195. }
  59196. if (byteArray) {
  59197. results.push(byteArray);
  59198. }
  59199. else {
  59200. results.push(dataFace);
  59201. }
  59202. }
  59203. return results;
  59204. };
  59205. var mipmapGenerator = null;
  59206. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  59207. // if (!this._noMipmap &&
  59208. // this._usePMREMGenerator) {
  59209. // mipmapGenerator = (data: ArrayBufferView[]) => {
  59210. // // Custom setup of the generator matching with the PBR shader values.
  59211. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  59212. // this._size,
  59213. // this._size,
  59214. // 0,
  59215. // 3,
  59216. // this.getScene().getEngine().getCaps().textureFloat,
  59217. // 2048,
  59218. // 0.25,
  59219. // false,
  59220. // true);
  59221. // return generator.filterCubeMap();
  59222. // };
  59223. // }
  59224. 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);
  59225. };
  59226. /**
  59227. * Starts the loading process of the texture.
  59228. */
  59229. HDRCubeTexture.prototype.loadTexture = function () {
  59230. if (this._isBABYLONPreprocessed) {
  59231. this.loadBabylonTexture();
  59232. }
  59233. else {
  59234. this.loadHDRTexture();
  59235. }
  59236. };
  59237. HDRCubeTexture.prototype.clone = function () {
  59238. var size = this._isBABYLONPreprocessed ? null : this._size;
  59239. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59240. // Base texture
  59241. newTexture.level = this.level;
  59242. newTexture.wrapU = this.wrapU;
  59243. newTexture.wrapV = this.wrapV;
  59244. newTexture.coordinatesIndex = this.coordinatesIndex;
  59245. newTexture.coordinatesMode = this.coordinatesMode;
  59246. return newTexture;
  59247. };
  59248. // Methods
  59249. HDRCubeTexture.prototype.delayLoad = function () {
  59250. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59251. return;
  59252. }
  59253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59254. this._texture = this._getFromCache(this.url, this._noMipmap);
  59255. if (!this._texture) {
  59256. this.loadTexture();
  59257. }
  59258. };
  59259. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59260. return this._textureMatrix;
  59261. };
  59262. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59263. this._textureMatrix = value;
  59264. };
  59265. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59266. var texture = null;
  59267. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59268. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59269. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  59270. texture.name = parsedTexture.name;
  59271. texture.hasAlpha = parsedTexture.hasAlpha;
  59272. texture.level = parsedTexture.level;
  59273. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59274. texture.isBlocking = parsedTexture.isBlocking;
  59275. }
  59276. return texture;
  59277. };
  59278. HDRCubeTexture.prototype.serialize = function () {
  59279. if (!this.name) {
  59280. return null;
  59281. }
  59282. var serializationObject = {};
  59283. serializationObject.name = this.name;
  59284. serializationObject.hasAlpha = this.hasAlpha;
  59285. serializationObject.isCube = true;
  59286. serializationObject.level = this.level;
  59287. serializationObject.size = this._size;
  59288. serializationObject.coordinatesMode = this.coordinatesMode;
  59289. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59290. serializationObject.generateHarmonics = this._generateHarmonics;
  59291. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59292. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59293. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59294. serializationObject.noMipmap = this._noMipmap;
  59295. serializationObject.isBlocking = this._isBlocking;
  59296. return serializationObject;
  59297. };
  59298. /**
  59299. * Saves as a file the data contained in the texture in a binary format.
  59300. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59301. * as the spherical used in the lighting.
  59302. * @param url The HDR file url.
  59303. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59304. * @param onError Method called if any error happens during download.
  59305. * @return The packed binary data.
  59306. */
  59307. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59308. if (onError === void 0) { onError = null; }
  59309. var callback = function (buffer) {
  59310. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59311. // Returns a URL you can use as a href.
  59312. var objUrl = window.URL.createObjectURL(data);
  59313. // Simulates a link to it and click to dowload.
  59314. var a = document.createElement("a");
  59315. document.body.appendChild(a);
  59316. a.style.display = "none";
  59317. a.href = objUrl;
  59318. a.download = "envmap.babylon.hdr";
  59319. a.click();
  59320. };
  59321. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59322. };
  59323. /**
  59324. * Serializes the data contained in the texture in a binary format.
  59325. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59326. * as the spherical used in the lighting.
  59327. * @param url The HDR file url.
  59328. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59329. * @param onError Method called if any error happens during download.
  59330. * @return The packed binary data.
  59331. */
  59332. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59333. if (onError === void 0) { onError = null; }
  59334. // Needs the url tho create the texture.
  59335. if (!url) {
  59336. return null;
  59337. }
  59338. // Check Power of two size.
  59339. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59340. return null;
  59341. }
  59342. // Coming Back in 3.1.
  59343. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  59344. return null;
  59345. };
  59346. HDRCubeTexture._facesMapping = [
  59347. "right",
  59348. "left",
  59349. "up",
  59350. "down",
  59351. "front",
  59352. "back"
  59353. ];
  59354. return HDRCubeTexture;
  59355. }(BABYLON.BaseTexture));
  59356. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59357. })(BABYLON || (BABYLON = {}));
  59358. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  59359. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  59360. // Huge respect for a such great lib.
  59361. // Earcut license:
  59362. // Copyright (c) 2016, Mapbox
  59363. //
  59364. // Permission to use, copy, modify, and/or distribute this software for any purpose
  59365. // with or without fee is hereby granted, provided that the above copyright notice
  59366. // and this permission notice appear in all copies.
  59367. //
  59368. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  59369. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  59370. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  59371. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  59372. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  59373. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  59374. // THIS SOFTWARE.
  59375. var Earcut;
  59376. (function (Earcut) {
  59377. /**
  59378. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  59379. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  59380. * @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).
  59381. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  59382. */
  59383. function earcut(data, holeIndices, dim) {
  59384. dim = dim || 2;
  59385. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  59386. if (!outerNode)
  59387. return triangles;
  59388. var minX, minY, maxX, maxY, x, y, size;
  59389. if (hasHoles)
  59390. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  59391. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  59392. if (data.length > 80 * dim) {
  59393. minX = maxX = data[0];
  59394. minY = maxY = data[1];
  59395. for (var i = dim; i < outerLen; i += dim) {
  59396. x = data[i];
  59397. y = data[i + 1];
  59398. if (x < minX)
  59399. minX = x;
  59400. if (y < minY)
  59401. minY = y;
  59402. if (x > maxX)
  59403. maxX = x;
  59404. if (y > maxY)
  59405. maxY = y;
  59406. }
  59407. // minX, minY and size are later used to transform coords into integers for z-order calculation
  59408. size = Math.max(maxX - minX, maxY - minY);
  59409. }
  59410. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  59411. return triangles;
  59412. }
  59413. Earcut.earcut = earcut;
  59414. // create a circular doubly linked list from polygon points in the specified winding order
  59415. function linkedList(data, start, end, dim, clockwise) {
  59416. var i, last;
  59417. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  59418. for (i = start; i < end; i += dim)
  59419. last = insertNode(i, data[i], data[i + 1], last);
  59420. }
  59421. else {
  59422. for (i = end - dim; i >= start; i -= dim)
  59423. last = insertNode(i, data[i], data[i + 1], last);
  59424. }
  59425. if (last && equals(last, last.next)) {
  59426. removeNode(last);
  59427. last = last.next;
  59428. }
  59429. return last;
  59430. }
  59431. // eliminate colinear or duplicate points
  59432. function filterPoints(start, end) {
  59433. if (!start)
  59434. return start;
  59435. if (!end)
  59436. end = start;
  59437. var p = start, again;
  59438. do {
  59439. again = false;
  59440. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  59441. removeNode(p);
  59442. p = end = p.prev;
  59443. if (p === p.next)
  59444. return null;
  59445. again = true;
  59446. }
  59447. else {
  59448. p = p.next;
  59449. }
  59450. } while (again || p !== end);
  59451. return end;
  59452. }
  59453. // main ear slicing loop which triangulates a polygon (given as a linked list)
  59454. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  59455. if (!ear)
  59456. return;
  59457. // interlink polygon nodes in z-order
  59458. if (!pass && size)
  59459. indexCurve(ear, minX, minY, size);
  59460. var stop = ear, prev, next;
  59461. // iterate through ears, slicing them one by one
  59462. while (ear.prev !== ear.next) {
  59463. prev = ear.prev;
  59464. next = ear.next;
  59465. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  59466. // cut off the triangle
  59467. triangles.push(prev.i / dim);
  59468. triangles.push(ear.i / dim);
  59469. triangles.push(next.i / dim);
  59470. removeNode(ear);
  59471. // skipping the next vertice leads to less sliver triangles
  59472. ear = next.next;
  59473. stop = next.next;
  59474. continue;
  59475. }
  59476. ear = next;
  59477. // if we looped through the whole remaining polygon and can't find any more ears
  59478. if (ear === stop) {
  59479. // try filtering points and slicing again
  59480. if (!pass) {
  59481. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  59482. // if this didn't work, try curing all small self-intersections locally
  59483. }
  59484. else if (pass === 1) {
  59485. ear = cureLocalIntersections(ear, triangles, dim);
  59486. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  59487. // as a last resort, try splitting the remaining polygon into two
  59488. }
  59489. else if (pass === 2) {
  59490. splitEarcut(ear, triangles, dim, minX, minY, size);
  59491. }
  59492. break;
  59493. }
  59494. }
  59495. }
  59496. // check whether a polygon node forms a valid ear with adjacent nodes
  59497. function isEar(ear) {
  59498. var a = ear.prev, b = ear, c = ear.next;
  59499. if (area(a, b, c) >= 0)
  59500. return false; // reflex, can't be an ear
  59501. // now make sure we don't have other points inside the potential ear
  59502. var p = ear.next.next;
  59503. while (p !== ear.prev) {
  59504. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59505. area(p.prev, p, p.next) >= 0)
  59506. return false;
  59507. p = p.next;
  59508. }
  59509. return true;
  59510. }
  59511. function isEarHashed(ear, minX, minY, size) {
  59512. var a = ear.prev, b = ear, c = ear.next;
  59513. if (area(a, b, c) >= 0)
  59514. return false; // reflex, can't be an ear
  59515. // triangle bbox; min & max are calculated like this for speed
  59516. 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);
  59517. // z-order range for the current triangle bbox;
  59518. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  59519. // first look for points inside the triangle in increasing z-order
  59520. var p = ear.nextZ;
  59521. while (p && p.z <= maxZ) {
  59522. if (p !== ear.prev &&
  59523. p !== ear.next &&
  59524. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59525. area(p.prev, p, p.next) >= 0)
  59526. return false;
  59527. p = p.nextZ;
  59528. }
  59529. // then look for points in decreasing z-order
  59530. p = ear.prevZ;
  59531. while (p && p.z >= minZ) {
  59532. if (p !== ear.prev &&
  59533. p !== ear.next &&
  59534. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59535. area(p.prev, p, p.next) >= 0)
  59536. return false;
  59537. p = p.prevZ;
  59538. }
  59539. return true;
  59540. }
  59541. // go through all polygon nodes and cure small local self-intersections
  59542. function cureLocalIntersections(start, triangles, dim) {
  59543. var p = start;
  59544. do {
  59545. var a = p.prev, b = p.next.next;
  59546. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  59547. triangles.push(a.i / dim);
  59548. triangles.push(p.i / dim);
  59549. triangles.push(b.i / dim);
  59550. // remove two nodes involved
  59551. removeNode(p);
  59552. removeNode(p.next);
  59553. p = start = b;
  59554. }
  59555. p = p.next;
  59556. } while (p !== start);
  59557. return p;
  59558. }
  59559. // try splitting polygon into two and triangulate them independently
  59560. function splitEarcut(start, triangles, dim, minX, minY, size) {
  59561. // look for a valid diagonal that divides the polygon into two
  59562. var a = start;
  59563. do {
  59564. var b = a.next.next;
  59565. while (b !== a.prev) {
  59566. if (a.i !== b.i && isValidDiagonal(a, b)) {
  59567. // split the polygon in two by the diagonal
  59568. var c = splitPolygon(a, b);
  59569. // filter colinear points around the cuts
  59570. a = filterPoints(a, a.next);
  59571. c = filterPoints(c, c.next);
  59572. // run earcut on each half
  59573. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  59574. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  59575. return;
  59576. }
  59577. b = b.next;
  59578. }
  59579. a = a.next;
  59580. } while (a !== start);
  59581. }
  59582. // link every hole into the outer loop, producing a single-ring polygon without holes
  59583. function eliminateHoles(data, holeIndices, outerNode, dim) {
  59584. var queue = [], i, len, start, end, list;
  59585. for (i = 0, len = holeIndices.length; i < len; i++) {
  59586. start = holeIndices[i] * dim;
  59587. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59588. list = linkedList(data, start, end, dim, false);
  59589. if (list === list.next)
  59590. list.steiner = true;
  59591. queue.push(getLeftmost(list));
  59592. }
  59593. queue.sort(compareX);
  59594. // process holes from left to right
  59595. for (i = 0; i < queue.length; i++) {
  59596. eliminateHole(queue[i], outerNode);
  59597. outerNode = filterPoints(outerNode, outerNode.next);
  59598. }
  59599. return outerNode;
  59600. }
  59601. function compareX(a, b) {
  59602. return a.x - b.x;
  59603. }
  59604. // find a bridge between vertices that connects hole with an outer ring and and link it
  59605. function eliminateHole(hole, outerNode) {
  59606. outerNode = findHoleBridge(hole, outerNode);
  59607. if (outerNode) {
  59608. var b = splitPolygon(outerNode, hole);
  59609. filterPoints(b, b.next);
  59610. }
  59611. }
  59612. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  59613. function findHoleBridge(hole, outerNode) {
  59614. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  59615. // find a segment intersected by a ray from the hole's leftmost point to the left;
  59616. // segment's endpoint with lesser x will be potential connection point
  59617. do {
  59618. if (hy <= p.y && hy >= p.next.y) {
  59619. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  59620. if (x <= hx && x > qx) {
  59621. qx = x;
  59622. if (x === hx) {
  59623. if (hy === p.y)
  59624. return p;
  59625. if (hy === p.next.y)
  59626. return p.next;
  59627. }
  59628. m = p.x < p.next.x ? p : p.next;
  59629. }
  59630. }
  59631. p = p.next;
  59632. } while (p !== outerNode);
  59633. if (!m)
  59634. return null;
  59635. if (hx === qx)
  59636. return m.prev; // hole touches outer segment; pick lower endpoint
  59637. // look for points inside the triangle of hole point, segment intersection and endpoint;
  59638. // if there are no points found, we have a valid connection;
  59639. // otherwise choose the point of the minimum angle with the ray as connection point
  59640. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  59641. p = m.next;
  59642. while (p !== stop) {
  59643. if (hx >= p.x &&
  59644. p.x >= mx &&
  59645. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  59646. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  59647. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  59648. m = p;
  59649. tanMin = tan;
  59650. }
  59651. }
  59652. p = p.next;
  59653. }
  59654. return m;
  59655. }
  59656. // interlink polygon nodes in z-order
  59657. function indexCurve(start, minX, minY, size) {
  59658. var p = start;
  59659. do {
  59660. if (p.z === null)
  59661. p.z = zOrder(p.x, p.y, minX, minY, size);
  59662. p.prevZ = p.prev;
  59663. p.nextZ = p.next;
  59664. p = p.next;
  59665. } while (p !== start);
  59666. p.prevZ.nextZ = null;
  59667. p.prevZ = null;
  59668. sortLinked(p);
  59669. }
  59670. // Simon Tatham's linked list merge sort algorithm
  59671. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  59672. function sortLinked(list) {
  59673. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  59674. do {
  59675. p = list;
  59676. list = null;
  59677. tail = null;
  59678. numMerges = 0;
  59679. while (p) {
  59680. numMerges++;
  59681. q = p;
  59682. pSize = 0;
  59683. for (i = 0; i < inSize; i++) {
  59684. pSize++;
  59685. q = q.nextZ;
  59686. if (!q)
  59687. break;
  59688. }
  59689. qSize = inSize;
  59690. while (pSize > 0 || (qSize > 0 && q)) {
  59691. if (pSize === 0) {
  59692. e = q;
  59693. q = q.nextZ;
  59694. qSize--;
  59695. }
  59696. else if (qSize === 0 || !q) {
  59697. e = p;
  59698. p = p.nextZ;
  59699. pSize--;
  59700. }
  59701. else if (p.z <= q.z) {
  59702. e = p;
  59703. p = p.nextZ;
  59704. pSize--;
  59705. }
  59706. else {
  59707. e = q;
  59708. q = q.nextZ;
  59709. qSize--;
  59710. }
  59711. if (tail)
  59712. tail.nextZ = e;
  59713. else
  59714. list = e;
  59715. e.prevZ = tail;
  59716. tail = e;
  59717. }
  59718. p = q;
  59719. }
  59720. tail.nextZ = null;
  59721. inSize *= 2;
  59722. } while (numMerges > 1);
  59723. return list;
  59724. }
  59725. // z-order of a point given coords and size of the data bounding box
  59726. function zOrder(x, y, minX, minY, size) {
  59727. // coords are transformed into non-negative 15-bit integer range
  59728. x = 32767 * (x - minX) / size;
  59729. y = 32767 * (y - minY) / size;
  59730. x = (x | (x << 8)) & 0x00FF00FF;
  59731. x = (x | (x << 4)) & 0x0F0F0F0F;
  59732. x = (x | (x << 2)) & 0x33333333;
  59733. x = (x | (x << 1)) & 0x55555555;
  59734. y = (y | (y << 8)) & 0x00FF00FF;
  59735. y = (y | (y << 4)) & 0x0F0F0F0F;
  59736. y = (y | (y << 2)) & 0x33333333;
  59737. y = (y | (y << 1)) & 0x55555555;
  59738. return x | (y << 1);
  59739. }
  59740. // find the leftmost node of a polygon ring
  59741. function getLeftmost(start) {
  59742. var p = start, leftmost = start;
  59743. do {
  59744. if (p.x < leftmost.x)
  59745. leftmost = p;
  59746. p = p.next;
  59747. } while (p !== start);
  59748. return leftmost;
  59749. }
  59750. // check if a point lies within a convex triangle
  59751. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  59752. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  59753. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  59754. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  59755. }
  59756. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  59757. function isValidDiagonal(a, b) {
  59758. return a.next.i !== b.i &&
  59759. a.prev.i !== b.i &&
  59760. !intersectsPolygon(a, b) &&
  59761. locallyInside(a, b) &&
  59762. locallyInside(b, a) &&
  59763. middleInside(a, b);
  59764. }
  59765. // signed area of a triangle
  59766. function area(p, q, r) {
  59767. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  59768. }
  59769. // check if two points are equal
  59770. function equals(p1, p2) {
  59771. return p1.x === p2.x && p1.y === p2.y;
  59772. }
  59773. // check if two segments intersect
  59774. function intersects(p1, q1, p2, q2) {
  59775. if ((equals(p1, q1) && equals(p2, q2)) ||
  59776. (equals(p1, q2) && equals(p2, q1)))
  59777. return true;
  59778. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  59779. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  59780. }
  59781. // check if a polygon diagonal intersects any polygon segments
  59782. function intersectsPolygon(a, b) {
  59783. var p = a;
  59784. do {
  59785. if (p.i !== a.i &&
  59786. p.next.i !== a.i &&
  59787. p.i !== b.i &&
  59788. p.next.i !== b.i &&
  59789. intersects(p, p.next, a, b))
  59790. return true;
  59791. p = p.next;
  59792. } while (p !== a);
  59793. return false;
  59794. }
  59795. // check if a polygon diagonal is locally inside the polygon
  59796. function locallyInside(a, b) {
  59797. return area(a.prev, a, a.next) < 0
  59798. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  59799. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  59800. }
  59801. // check if the middle point of a polygon diagonal is inside the polygon
  59802. function middleInside(a, b) {
  59803. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  59804. do {
  59805. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  59806. inside = !inside;
  59807. p = p.next;
  59808. } while (p !== a);
  59809. return inside;
  59810. }
  59811. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  59812. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  59813. function splitPolygon(a, b) {
  59814. 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;
  59815. a.next = b;
  59816. b.prev = a;
  59817. a2.next = an;
  59818. an.prev = a2;
  59819. b2.next = a2;
  59820. a2.prev = b2;
  59821. bp.next = b2;
  59822. b2.prev = bp;
  59823. return b2;
  59824. }
  59825. // create a node and optionally link it with previous one (in a circular doubly linked list)
  59826. function insertNode(i, x, y, last) {
  59827. var p = new Node(i, x, y);
  59828. if (!last) {
  59829. p.prev = p;
  59830. p.next = p;
  59831. }
  59832. else {
  59833. p.next = last.next;
  59834. p.prev = last;
  59835. last.next.prev = p;
  59836. last.next = p;
  59837. }
  59838. return p;
  59839. }
  59840. function removeNode(p) {
  59841. p.next.prev = p.prev;
  59842. p.prev.next = p.next;
  59843. if (p.prevZ)
  59844. p.prevZ.nextZ = p.nextZ;
  59845. if (p.nextZ)
  59846. p.nextZ.prevZ = p.prevZ;
  59847. }
  59848. function Node(i, x, y) {
  59849. // vertice index in coordinates array
  59850. this.i = i;
  59851. // vertex coordinates
  59852. this.x = x;
  59853. this.y = y;
  59854. // previous and next vertice nodes in a polygon ring
  59855. this.prev = null;
  59856. this.next = null;
  59857. // z-order curve value
  59858. this.z = null;
  59859. // previous and next nodes in z-order
  59860. this.prevZ = null;
  59861. this.nextZ = null;
  59862. // indicates whether this is a steiner point
  59863. this.steiner = false;
  59864. }
  59865. /**
  59866. * return a percentage difference between the polygon area and its triangulation area;
  59867. * used to verify correctness of triangulation
  59868. */
  59869. function deviation(data, holeIndices, dim, triangles) {
  59870. var hasHoles = holeIndices && holeIndices.length;
  59871. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  59872. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  59873. if (hasHoles) {
  59874. for (var i = 0, len = holeIndices.length; i < len; i++) {
  59875. var start = holeIndices[i] * dim;
  59876. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59877. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  59878. }
  59879. }
  59880. var trianglesArea = 0;
  59881. for (i = 0; i < triangles.length; i += 3) {
  59882. var a = triangles[i] * dim;
  59883. var b = triangles[i + 1] * dim;
  59884. var c = triangles[i + 2] * dim;
  59885. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  59886. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  59887. }
  59888. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  59889. }
  59890. Earcut.deviation = deviation;
  59891. ;
  59892. function signedArea(data, start, end, dim) {
  59893. var sum = 0;
  59894. for (var i = start, j = end - dim; i < end; i += dim) {
  59895. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  59896. j = i;
  59897. }
  59898. return sum;
  59899. }
  59900. /**
  59901. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  59902. */
  59903. function flatten(data) {
  59904. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  59905. for (var i = 0; i < data.length; i++) {
  59906. for (var j = 0; j < data[i].length; j++) {
  59907. for (var d = 0; d < dim; d++)
  59908. result.vertices.push(data[i][j][d]);
  59909. }
  59910. if (i > 0) {
  59911. holeIndex += data[i - 1].length;
  59912. result.holes.push(holeIndex);
  59913. }
  59914. }
  59915. return result;
  59916. }
  59917. Earcut.flatten = flatten;
  59918. ;
  59919. })(Earcut || (Earcut = {}));
  59920. //# sourceMappingURL=babylon.earcut.js.map
  59921. /// <reference path="..\Math\babylon.math.ts" />
  59922. var BABYLON;
  59923. (function (BABYLON) {
  59924. var IndexedVector2 = (function (_super) {
  59925. __extends(IndexedVector2, _super);
  59926. function IndexedVector2(original, index) {
  59927. var _this = _super.call(this, original.x, original.y) || this;
  59928. _this.index = index;
  59929. return _this;
  59930. }
  59931. return IndexedVector2;
  59932. }(BABYLON.Vector2));
  59933. var PolygonPoints = (function () {
  59934. function PolygonPoints() {
  59935. this.elements = new Array();
  59936. }
  59937. PolygonPoints.prototype.add = function (originalPoints) {
  59938. var _this = this;
  59939. var result = new Array();
  59940. originalPoints.forEach(function (point) {
  59941. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  59942. var newPoint = new IndexedVector2(point, _this.elements.length);
  59943. result.push(newPoint);
  59944. _this.elements.push(newPoint);
  59945. }
  59946. });
  59947. return result;
  59948. };
  59949. PolygonPoints.prototype.computeBounds = function () {
  59950. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59951. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59952. this.elements.forEach(function (point) {
  59953. // x
  59954. if (point.x < lmin.x) {
  59955. lmin.x = point.x;
  59956. }
  59957. else if (point.x > lmax.x) {
  59958. lmax.x = point.x;
  59959. }
  59960. // y
  59961. if (point.y < lmin.y) {
  59962. lmin.y = point.y;
  59963. }
  59964. else if (point.y > lmax.y) {
  59965. lmax.y = point.y;
  59966. }
  59967. });
  59968. return {
  59969. min: lmin,
  59970. max: lmax,
  59971. width: lmax.x - lmin.x,
  59972. height: lmax.y - lmin.y
  59973. };
  59974. };
  59975. return PolygonPoints;
  59976. }());
  59977. var Polygon = (function () {
  59978. function Polygon() {
  59979. }
  59980. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  59981. return [
  59982. new BABYLON.Vector2(xmin, ymin),
  59983. new BABYLON.Vector2(xmax, ymin),
  59984. new BABYLON.Vector2(xmax, ymax),
  59985. new BABYLON.Vector2(xmin, ymax)
  59986. ];
  59987. };
  59988. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  59989. if (cx === void 0) { cx = 0; }
  59990. if (cy === void 0) { cy = 0; }
  59991. if (numberOfSides === void 0) { numberOfSides = 32; }
  59992. var result = new Array();
  59993. var angle = 0;
  59994. var increment = (Math.PI * 2) / numberOfSides;
  59995. for (var i = 0; i < numberOfSides; i++) {
  59996. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  59997. angle -= increment;
  59998. }
  59999. return result;
  60000. };
  60001. Polygon.Parse = function (input) {
  60002. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  60003. var i, result = [];
  60004. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  60005. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  60006. }
  60007. return result;
  60008. };
  60009. Polygon.StartingAt = function (x, y) {
  60010. return BABYLON.Path2.StartingAt(x, y);
  60011. };
  60012. return Polygon;
  60013. }());
  60014. BABYLON.Polygon = Polygon;
  60015. var PolygonMeshBuilder = (function () {
  60016. function PolygonMeshBuilder(name, contours, scene) {
  60017. this._points = new PolygonPoints();
  60018. this._outlinepoints = new PolygonPoints();
  60019. this._holes = [];
  60020. this._epoints = new Array();
  60021. this._eholes = new Array();
  60022. this._name = name;
  60023. this._scene = scene;
  60024. var points;
  60025. if (contours instanceof BABYLON.Path2) {
  60026. points = contours.getPoints();
  60027. }
  60028. else {
  60029. points = contours;
  60030. }
  60031. this._addToepoint(points);
  60032. this._points.add(points);
  60033. this._outlinepoints.add(points);
  60034. }
  60035. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  60036. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  60037. var p = points_1[_i];
  60038. this._epoints.push(p.x, p.y);
  60039. }
  60040. };
  60041. PolygonMeshBuilder.prototype.addHole = function (hole) {
  60042. this._points.add(hole);
  60043. var holepoints = new PolygonPoints();
  60044. holepoints.add(hole);
  60045. this._holes.push(holepoints);
  60046. this._eholes.push(this._epoints.length / 2);
  60047. this._addToepoint(hole);
  60048. return this;
  60049. };
  60050. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  60051. var _this = this;
  60052. if (updatable === void 0) { updatable = false; }
  60053. var result = new BABYLON.Mesh(this._name, this._scene);
  60054. var normals = [];
  60055. var positions = [];
  60056. var uvs = [];
  60057. var bounds = this._points.computeBounds();
  60058. this._points.elements.forEach(function (p) {
  60059. normals.push(0, 1.0, 0);
  60060. positions.push(p.x, 0, p.y);
  60061. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  60062. });
  60063. var indices = [];
  60064. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  60065. for (var i = 0; i < res.length; i++) {
  60066. indices.push(res[i]);
  60067. }
  60068. if (depth > 0) {
  60069. var positionscount = (positions.length / 3); //get the current pointcount
  60070. this._points.elements.forEach(function (p) {
  60071. normals.push(0, -1.0, 0);
  60072. positions.push(p.x, -depth, p.y);
  60073. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  60074. });
  60075. var totalCount = indices.length;
  60076. for (var i = 0; i < totalCount; i += 3) {
  60077. var i0 = indices[i + 0];
  60078. var i1 = indices[i + 1];
  60079. var i2 = indices[i + 2];
  60080. indices.push(i2 + positionscount);
  60081. indices.push(i1 + positionscount);
  60082. indices.push(i0 + positionscount);
  60083. }
  60084. //Add the sides
  60085. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  60086. this._holes.forEach(function (hole) {
  60087. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  60088. });
  60089. }
  60090. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  60091. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  60092. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  60093. result.setIndices(indices);
  60094. return result;
  60095. };
  60096. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  60097. var StartIndex = positions.length / 3;
  60098. var ulength = 0;
  60099. for (var i = 0; i < points.elements.length; i++) {
  60100. var p = points.elements[i];
  60101. var p1;
  60102. if ((i + 1) > points.elements.length - 1) {
  60103. p1 = points.elements[0];
  60104. }
  60105. else {
  60106. p1 = points.elements[i + 1];
  60107. }
  60108. positions.push(p.x, 0, p.y);
  60109. positions.push(p.x, -depth, p.y);
  60110. positions.push(p1.x, 0, p1.y);
  60111. positions.push(p1.x, -depth, p1.y);
  60112. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  60113. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  60114. var v3 = v2.subtract(v1);
  60115. var v4 = new BABYLON.Vector3(0, 1, 0);
  60116. var vn = BABYLON.Vector3.Cross(v3, v4);
  60117. vn = vn.normalize();
  60118. uvs.push(ulength / bounds.width, 0);
  60119. uvs.push(ulength / bounds.width, 1);
  60120. ulength += v3.length();
  60121. uvs.push((ulength / bounds.width), 0);
  60122. uvs.push((ulength / bounds.width), 1);
  60123. if (!flip) {
  60124. normals.push(-vn.x, -vn.y, -vn.z);
  60125. normals.push(-vn.x, -vn.y, -vn.z);
  60126. normals.push(-vn.x, -vn.y, -vn.z);
  60127. normals.push(-vn.x, -vn.y, -vn.z);
  60128. indices.push(StartIndex);
  60129. indices.push(StartIndex + 1);
  60130. indices.push(StartIndex + 2);
  60131. indices.push(StartIndex + 1);
  60132. indices.push(StartIndex + 3);
  60133. indices.push(StartIndex + 2);
  60134. }
  60135. else {
  60136. normals.push(vn.x, vn.y, vn.z);
  60137. normals.push(vn.x, vn.y, vn.z);
  60138. normals.push(vn.x, vn.y, vn.z);
  60139. normals.push(vn.x, vn.y, vn.z);
  60140. indices.push(StartIndex);
  60141. indices.push(StartIndex + 2);
  60142. indices.push(StartIndex + 1);
  60143. indices.push(StartIndex + 1);
  60144. indices.push(StartIndex + 2);
  60145. indices.push(StartIndex + 3);
  60146. }
  60147. StartIndex += 4;
  60148. }
  60149. ;
  60150. };
  60151. return PolygonMeshBuilder;
  60152. }());
  60153. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  60154. })(BABYLON || (BABYLON = {}));
  60155. //# sourceMappingURL=babylon.polygonMesh.js.map
  60156. var BABYLON;
  60157. (function (BABYLON) {
  60158. // Unique ID when we import meshes from Babylon to CSG
  60159. var currentCSGMeshId = 0;
  60160. // # class Vertex
  60161. // Represents a vertex of a polygon. Use your own vertex class instead of this
  60162. // one to provide additional features like texture coordinates and vertex
  60163. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  60164. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  60165. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  60166. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  60167. // is not used anywhere else.
  60168. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  60169. var Vertex = (function () {
  60170. function Vertex(pos, normal, uv) {
  60171. this.pos = pos;
  60172. this.normal = normal;
  60173. this.uv = uv;
  60174. }
  60175. Vertex.prototype.clone = function () {
  60176. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  60177. };
  60178. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  60179. // orientation of a polygon is flipped.
  60180. Vertex.prototype.flip = function () {
  60181. this.normal = this.normal.scale(-1);
  60182. };
  60183. // Create a new vertex between this vertex and `other` by linearly
  60184. // interpolating all properties using a parameter of `t`. Subclasses should
  60185. // override this to interpolate additional properties.
  60186. Vertex.prototype.interpolate = function (other, t) {
  60187. 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));
  60188. };
  60189. return Vertex;
  60190. }());
  60191. // # class Plane
  60192. // Represents a plane in 3D space.
  60193. var Plane = (function () {
  60194. function Plane(normal, w) {
  60195. this.normal = normal;
  60196. this.w = w;
  60197. }
  60198. Plane.FromPoints = function (a, b, c) {
  60199. var v0 = c.subtract(a);
  60200. var v1 = b.subtract(a);
  60201. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  60202. return null;
  60203. }
  60204. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  60205. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  60206. };
  60207. Plane.prototype.clone = function () {
  60208. return new Plane(this.normal.clone(), this.w);
  60209. };
  60210. Plane.prototype.flip = function () {
  60211. this.normal.scaleInPlace(-1);
  60212. this.w = -this.w;
  60213. };
  60214. // Split `polygon` by this plane if needed, then put the polygon or polygon
  60215. // fragments in the appropriate lists. Coplanar polygons go into either
  60216. // `coplanarFront` or `coplanarBack` depending on their orientation with
  60217. // respect to this plane. Polygons in front or in back of this plane go into
  60218. // either `front` or `back`.
  60219. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  60220. var COPLANAR = 0;
  60221. var FRONT = 1;
  60222. var BACK = 2;
  60223. var SPANNING = 3;
  60224. // Classify each point as well as the entire polygon into one of the above
  60225. // four classes.
  60226. var polygonType = 0;
  60227. var types = [];
  60228. var i;
  60229. var t;
  60230. for (i = 0; i < polygon.vertices.length; i++) {
  60231. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  60232. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  60233. polygonType |= type;
  60234. types.push(type);
  60235. }
  60236. // Put the polygon in the correct list, splitting it when necessary.
  60237. switch (polygonType) {
  60238. case COPLANAR:
  60239. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  60240. break;
  60241. case FRONT:
  60242. front.push(polygon);
  60243. break;
  60244. case BACK:
  60245. back.push(polygon);
  60246. break;
  60247. case SPANNING:
  60248. var f = [], b = [];
  60249. for (i = 0; i < polygon.vertices.length; i++) {
  60250. var j = (i + 1) % polygon.vertices.length;
  60251. var ti = types[i], tj = types[j];
  60252. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  60253. if (ti !== BACK)
  60254. f.push(vi);
  60255. if (ti !== FRONT)
  60256. b.push(ti !== BACK ? vi.clone() : vi);
  60257. if ((ti | tj) === SPANNING) {
  60258. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  60259. var v = vi.interpolate(vj, t);
  60260. f.push(v);
  60261. b.push(v.clone());
  60262. }
  60263. }
  60264. var poly;
  60265. if (f.length >= 3) {
  60266. poly = new Polygon(f, polygon.shared);
  60267. if (poly.plane)
  60268. front.push(poly);
  60269. }
  60270. if (b.length >= 3) {
  60271. poly = new Polygon(b, polygon.shared);
  60272. if (poly.plane)
  60273. back.push(poly);
  60274. }
  60275. break;
  60276. }
  60277. };
  60278. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  60279. // point is on the plane.
  60280. Plane.EPSILON = 1e-5;
  60281. return Plane;
  60282. }());
  60283. // # class Polygon
  60284. // Represents a convex polygon. The vertices used to initialize a polygon must
  60285. // be coplanar and form a convex loop.
  60286. //
  60287. // Each convex polygon has a `shared` property, which is shared between all
  60288. // polygons that are clones of each other or were split from the same polygon.
  60289. // This can be used to define per-polygon properties (such as surface color).
  60290. var Polygon = (function () {
  60291. function Polygon(vertices, shared) {
  60292. this.vertices = vertices;
  60293. this.shared = shared;
  60294. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  60295. }
  60296. Polygon.prototype.clone = function () {
  60297. var vertices = this.vertices.map(function (v) { return v.clone(); });
  60298. return new Polygon(vertices, this.shared);
  60299. };
  60300. Polygon.prototype.flip = function () {
  60301. this.vertices.reverse().map(function (v) { v.flip(); });
  60302. this.plane.flip();
  60303. };
  60304. return Polygon;
  60305. }());
  60306. // # class Node
  60307. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  60308. // by picking a polygon to split along. That polygon (and all other coplanar
  60309. // polygons) are added directly to that node and the other polygons are added to
  60310. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  60311. // no distinction between internal and leaf nodes.
  60312. var Node = (function () {
  60313. function Node(polygons) {
  60314. this.plane = null;
  60315. this.front = null;
  60316. this.back = null;
  60317. this.polygons = [];
  60318. if (polygons) {
  60319. this.build(polygons);
  60320. }
  60321. }
  60322. Node.prototype.clone = function () {
  60323. var node = new Node();
  60324. node.plane = this.plane && this.plane.clone();
  60325. node.front = this.front && this.front.clone();
  60326. node.back = this.back && this.back.clone();
  60327. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  60328. return node;
  60329. };
  60330. // Convert solid space to empty space and empty space to solid space.
  60331. Node.prototype.invert = function () {
  60332. for (var i = 0; i < this.polygons.length; i++) {
  60333. this.polygons[i].flip();
  60334. }
  60335. if (this.plane) {
  60336. this.plane.flip();
  60337. }
  60338. if (this.front) {
  60339. this.front.invert();
  60340. }
  60341. if (this.back) {
  60342. this.back.invert();
  60343. }
  60344. var temp = this.front;
  60345. this.front = this.back;
  60346. this.back = temp;
  60347. };
  60348. // Recursively remove all polygons in `polygons` that are inside this BSP
  60349. // tree.
  60350. Node.prototype.clipPolygons = function (polygons) {
  60351. if (!this.plane)
  60352. return polygons.slice();
  60353. var front = [], back = [];
  60354. for (var i = 0; i < polygons.length; i++) {
  60355. this.plane.splitPolygon(polygons[i], front, back, front, back);
  60356. }
  60357. if (this.front) {
  60358. front = this.front.clipPolygons(front);
  60359. }
  60360. if (this.back) {
  60361. back = this.back.clipPolygons(back);
  60362. }
  60363. else {
  60364. back = [];
  60365. }
  60366. return front.concat(back);
  60367. };
  60368. // Remove all polygons in this BSP tree that are inside the other BSP tree
  60369. // `bsp`.
  60370. Node.prototype.clipTo = function (bsp) {
  60371. this.polygons = bsp.clipPolygons(this.polygons);
  60372. if (this.front)
  60373. this.front.clipTo(bsp);
  60374. if (this.back)
  60375. this.back.clipTo(bsp);
  60376. };
  60377. // Return a list of all polygons in this BSP tree.
  60378. Node.prototype.allPolygons = function () {
  60379. var polygons = this.polygons.slice();
  60380. if (this.front)
  60381. polygons = polygons.concat(this.front.allPolygons());
  60382. if (this.back)
  60383. polygons = polygons.concat(this.back.allPolygons());
  60384. return polygons;
  60385. };
  60386. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  60387. // new polygons are filtered down to the bottom of the tree and become new
  60388. // nodes there. Each set of polygons is partitioned using the first polygon
  60389. // (no heuristic is used to pick a good split).
  60390. Node.prototype.build = function (polygons) {
  60391. if (!polygons.length)
  60392. return;
  60393. if (!this.plane)
  60394. this.plane = polygons[0].plane.clone();
  60395. var front = [], back = [];
  60396. for (var i = 0; i < polygons.length; i++) {
  60397. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  60398. }
  60399. if (front.length) {
  60400. if (!this.front)
  60401. this.front = new Node();
  60402. this.front.build(front);
  60403. }
  60404. if (back.length) {
  60405. if (!this.back)
  60406. this.back = new Node();
  60407. this.back.build(back);
  60408. }
  60409. };
  60410. return Node;
  60411. }());
  60412. var CSG = (function () {
  60413. function CSG() {
  60414. this.polygons = new Array();
  60415. }
  60416. // Convert BABYLON.Mesh to BABYLON.CSG
  60417. CSG.FromMesh = function (mesh) {
  60418. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  60419. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  60420. if (mesh instanceof BABYLON.Mesh) {
  60421. mesh.computeWorldMatrix(true);
  60422. matrix = mesh.getWorldMatrix();
  60423. meshPosition = mesh.position.clone();
  60424. meshRotation = mesh.rotation.clone();
  60425. if (mesh.rotationQuaternion) {
  60426. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  60427. }
  60428. meshScaling = mesh.scaling.clone();
  60429. }
  60430. else {
  60431. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  60432. }
  60433. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60434. var subMeshes = mesh.subMeshes;
  60435. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  60436. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  60437. vertices = [];
  60438. for (var j = 0; j < 3; j++) {
  60439. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  60440. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  60441. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  60442. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  60443. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  60444. vertex = new Vertex(position, normal, uv);
  60445. vertices.push(vertex);
  60446. }
  60447. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  60448. // To handle the case of degenerated triangle
  60449. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  60450. if (polygon.plane)
  60451. polygons.push(polygon);
  60452. }
  60453. }
  60454. var csg = CSG.FromPolygons(polygons);
  60455. csg.matrix = matrix;
  60456. csg.position = meshPosition;
  60457. csg.rotation = meshRotation;
  60458. csg.scaling = meshScaling;
  60459. csg.rotationQuaternion = meshRotationQuaternion;
  60460. currentCSGMeshId++;
  60461. return csg;
  60462. };
  60463. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  60464. CSG.FromPolygons = function (polygons) {
  60465. var csg = new CSG();
  60466. csg.polygons = polygons;
  60467. return csg;
  60468. };
  60469. CSG.prototype.clone = function () {
  60470. var csg = new CSG();
  60471. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  60472. csg.copyTransformAttributes(this);
  60473. return csg;
  60474. };
  60475. CSG.prototype.toPolygons = function () {
  60476. return this.polygons;
  60477. };
  60478. CSG.prototype.union = function (csg) {
  60479. var a = new Node(this.clone().polygons);
  60480. var b = new Node(csg.clone().polygons);
  60481. a.clipTo(b);
  60482. b.clipTo(a);
  60483. b.invert();
  60484. b.clipTo(a);
  60485. b.invert();
  60486. a.build(b.allPolygons());
  60487. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60488. };
  60489. CSG.prototype.unionInPlace = function (csg) {
  60490. var a = new Node(this.polygons);
  60491. var b = new Node(csg.polygons);
  60492. a.clipTo(b);
  60493. b.clipTo(a);
  60494. b.invert();
  60495. b.clipTo(a);
  60496. b.invert();
  60497. a.build(b.allPolygons());
  60498. this.polygons = a.allPolygons();
  60499. };
  60500. CSG.prototype.subtract = function (csg) {
  60501. var a = new Node(this.clone().polygons);
  60502. var b = new Node(csg.clone().polygons);
  60503. a.invert();
  60504. a.clipTo(b);
  60505. b.clipTo(a);
  60506. b.invert();
  60507. b.clipTo(a);
  60508. b.invert();
  60509. a.build(b.allPolygons());
  60510. a.invert();
  60511. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60512. };
  60513. CSG.prototype.subtractInPlace = function (csg) {
  60514. var a = new Node(this.polygons);
  60515. var b = new Node(csg.polygons);
  60516. a.invert();
  60517. a.clipTo(b);
  60518. b.clipTo(a);
  60519. b.invert();
  60520. b.clipTo(a);
  60521. b.invert();
  60522. a.build(b.allPolygons());
  60523. a.invert();
  60524. this.polygons = a.allPolygons();
  60525. };
  60526. CSG.prototype.intersect = function (csg) {
  60527. var a = new Node(this.clone().polygons);
  60528. var b = new Node(csg.clone().polygons);
  60529. a.invert();
  60530. b.clipTo(a);
  60531. b.invert();
  60532. a.clipTo(b);
  60533. b.clipTo(a);
  60534. a.build(b.allPolygons());
  60535. a.invert();
  60536. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60537. };
  60538. CSG.prototype.intersectInPlace = function (csg) {
  60539. var a = new Node(this.polygons);
  60540. var b = new Node(csg.polygons);
  60541. a.invert();
  60542. b.clipTo(a);
  60543. b.invert();
  60544. a.clipTo(b);
  60545. b.clipTo(a);
  60546. a.build(b.allPolygons());
  60547. a.invert();
  60548. this.polygons = a.allPolygons();
  60549. };
  60550. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  60551. // not modified.
  60552. CSG.prototype.inverse = function () {
  60553. var csg = this.clone();
  60554. csg.inverseInPlace();
  60555. return csg;
  60556. };
  60557. CSG.prototype.inverseInPlace = function () {
  60558. this.polygons.map(function (p) { p.flip(); });
  60559. };
  60560. // This is used to keep meshes transformations so they can be restored
  60561. // when we build back a Babylon Mesh
  60562. // NB : All CSG operations are performed in world coordinates
  60563. CSG.prototype.copyTransformAttributes = function (csg) {
  60564. this.matrix = csg.matrix;
  60565. this.position = csg.position;
  60566. this.rotation = csg.rotation;
  60567. this.scaling = csg.scaling;
  60568. this.rotationQuaternion = csg.rotationQuaternion;
  60569. return this;
  60570. };
  60571. // Build Raw mesh from CSG
  60572. // Coordinates here are in world space
  60573. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  60574. var matrix = this.matrix.clone();
  60575. matrix.invert();
  60576. 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;
  60577. if (keepSubMeshes) {
  60578. // Sort Polygons, since subMeshes are indices range
  60579. polygons.sort(function (a, b) {
  60580. if (a.shared.meshId === b.shared.meshId) {
  60581. return a.shared.subMeshId - b.shared.subMeshId;
  60582. }
  60583. else {
  60584. return a.shared.meshId - b.shared.meshId;
  60585. }
  60586. });
  60587. }
  60588. for (var i = 0, il = polygons.length; i < il; i++) {
  60589. polygon = polygons[i];
  60590. // Building SubMeshes
  60591. if (!subMesh_dict[polygon.shared.meshId]) {
  60592. subMesh_dict[polygon.shared.meshId] = {};
  60593. }
  60594. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  60595. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  60596. indexStart: +Infinity,
  60597. indexEnd: -Infinity,
  60598. materialIndex: polygon.shared.materialIndex
  60599. };
  60600. }
  60601. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  60602. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  60603. polygonIndices[0] = 0;
  60604. polygonIndices[1] = j - 1;
  60605. polygonIndices[2] = j;
  60606. for (var k = 0; k < 3; k++) {
  60607. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  60608. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  60609. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  60610. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  60611. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  60612. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  60613. // Check if 2 points can be merged
  60614. if (!(typeof vertex_idx !== 'undefined' &&
  60615. normals[vertex_idx * 3] === localNormal.x &&
  60616. normals[vertex_idx * 3 + 1] === localNormal.y &&
  60617. normals[vertex_idx * 3 + 2] === localNormal.z &&
  60618. uvs[vertex_idx * 2] === uv.x &&
  60619. uvs[vertex_idx * 2 + 1] === uv.y)) {
  60620. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  60621. uvs.push(uv.x, uv.y);
  60622. normals.push(normal.x, normal.y, normal.z);
  60623. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  60624. }
  60625. indices.push(vertex_idx);
  60626. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  60627. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  60628. currentIndex++;
  60629. }
  60630. }
  60631. }
  60632. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  60633. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  60634. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  60635. mesh.setIndices(indices);
  60636. if (keepSubMeshes) {
  60637. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  60638. var materialIndexOffset = 0, materialMaxIndex;
  60639. mesh.subMeshes = new Array();
  60640. for (var m in subMesh_dict) {
  60641. materialMaxIndex = -1;
  60642. for (var sm in subMesh_dict[m]) {
  60643. subMesh_obj = subMesh_dict[m][sm];
  60644. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  60645. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  60646. }
  60647. materialIndexOffset += ++materialMaxIndex;
  60648. }
  60649. }
  60650. return mesh;
  60651. };
  60652. // Build Mesh from CSG taking material and transforms into account
  60653. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  60654. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  60655. mesh.material = material;
  60656. mesh.position.copyFrom(this.position);
  60657. mesh.rotation.copyFrom(this.rotation);
  60658. if (this.rotationQuaternion) {
  60659. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  60660. }
  60661. mesh.scaling.copyFrom(this.scaling);
  60662. mesh.computeWorldMatrix(true);
  60663. return mesh;
  60664. };
  60665. return CSG;
  60666. }());
  60667. BABYLON.CSG = CSG;
  60668. })(BABYLON || (BABYLON = {}));
  60669. //# sourceMappingURL=babylon.csg.js.map
  60670. var BABYLON;
  60671. (function (BABYLON) {
  60672. var LensFlare = (function () {
  60673. function LensFlare(size, position, color, imgUrl, system) {
  60674. this.size = size;
  60675. this.position = position;
  60676. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  60677. this.dispose = function () {
  60678. if (this.texture) {
  60679. this.texture.dispose();
  60680. }
  60681. // Remove from scene
  60682. var index = this._system.lensFlares.indexOf(this);
  60683. this._system.lensFlares.splice(index, 1);
  60684. };
  60685. this.color = color || new BABYLON.Color3(1, 1, 1);
  60686. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  60687. this._system = system;
  60688. system.lensFlares.push(this);
  60689. }
  60690. return LensFlare;
  60691. }());
  60692. BABYLON.LensFlare = LensFlare;
  60693. })(BABYLON || (BABYLON = {}));
  60694. //# sourceMappingURL=babylon.lensFlare.js.map
  60695. var BABYLON;
  60696. (function (BABYLON) {
  60697. var LensFlareSystem = (function () {
  60698. function LensFlareSystem(name, emitter, scene) {
  60699. this.name = name;
  60700. this.lensFlares = new Array();
  60701. this.borderLimit = 300;
  60702. this.viewportBorder = 0;
  60703. this.layerMask = 0x0FFFFFFF;
  60704. this._vertexBuffers = {};
  60705. this._isEnabled = true;
  60706. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60707. this._emitter = emitter;
  60708. this.id = name;
  60709. scene.lensFlareSystems.push(this);
  60710. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  60711. var engine = scene.getEngine();
  60712. // VBO
  60713. var vertices = [];
  60714. vertices.push(1, 1);
  60715. vertices.push(-1, 1);
  60716. vertices.push(-1, -1);
  60717. vertices.push(1, -1);
  60718. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60719. // Indices
  60720. var indices = [];
  60721. indices.push(0);
  60722. indices.push(1);
  60723. indices.push(2);
  60724. indices.push(0);
  60725. indices.push(2);
  60726. indices.push(3);
  60727. this._indexBuffer = engine.createIndexBuffer(indices);
  60728. // Effects
  60729. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  60730. }
  60731. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  60732. get: function () {
  60733. return this._isEnabled;
  60734. },
  60735. set: function (value) {
  60736. this._isEnabled = value;
  60737. },
  60738. enumerable: true,
  60739. configurable: true
  60740. });
  60741. LensFlareSystem.prototype.getScene = function () {
  60742. return this._scene;
  60743. };
  60744. LensFlareSystem.prototype.getEmitter = function () {
  60745. return this._emitter;
  60746. };
  60747. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  60748. this._emitter = newEmitter;
  60749. };
  60750. LensFlareSystem.prototype.getEmitterPosition = function () {
  60751. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  60752. };
  60753. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  60754. var position = this.getEmitterPosition();
  60755. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  60756. this._positionX = position.x;
  60757. this._positionY = position.y;
  60758. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  60759. if (this.viewportBorder > 0) {
  60760. globalViewport.x -= this.viewportBorder;
  60761. globalViewport.y -= this.viewportBorder;
  60762. globalViewport.width += this.viewportBorder * 2;
  60763. globalViewport.height += this.viewportBorder * 2;
  60764. position.x += this.viewportBorder;
  60765. position.y += this.viewportBorder;
  60766. this._positionX += this.viewportBorder;
  60767. this._positionY += this.viewportBorder;
  60768. }
  60769. if (position.z > 0) {
  60770. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  60771. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  60772. return true;
  60773. }
  60774. return true;
  60775. }
  60776. return false;
  60777. };
  60778. LensFlareSystem.prototype._isVisible = function () {
  60779. if (!this._isEnabled) {
  60780. return false;
  60781. }
  60782. var emitterPosition = this.getEmitterPosition();
  60783. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  60784. var distance = direction.length();
  60785. direction.normalize();
  60786. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  60787. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  60788. return !pickInfo.hit || pickInfo.distance > distance;
  60789. };
  60790. LensFlareSystem.prototype.render = function () {
  60791. if (!this._effect.isReady())
  60792. return false;
  60793. var engine = this._scene.getEngine();
  60794. var viewport = this._scene.activeCamera.viewport;
  60795. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  60796. // Position
  60797. if (!this.computeEffectivePosition(globalViewport)) {
  60798. return false;
  60799. }
  60800. // Visibility
  60801. if (!this._isVisible()) {
  60802. return false;
  60803. }
  60804. // Intensity
  60805. var awayX;
  60806. var awayY;
  60807. if (this._positionX < this.borderLimit + globalViewport.x) {
  60808. awayX = this.borderLimit + globalViewport.x - this._positionX;
  60809. }
  60810. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  60811. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  60812. }
  60813. else {
  60814. awayX = 0;
  60815. }
  60816. if (this._positionY < this.borderLimit + globalViewport.y) {
  60817. awayY = this.borderLimit + globalViewport.y - this._positionY;
  60818. }
  60819. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  60820. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  60821. }
  60822. else {
  60823. awayY = 0;
  60824. }
  60825. var away = (awayX > awayY) ? awayX : awayY;
  60826. away -= this.viewportBorder;
  60827. if (away > this.borderLimit) {
  60828. away = this.borderLimit;
  60829. }
  60830. var intensity = 1.0 - (away / this.borderLimit);
  60831. if (intensity < 0) {
  60832. return false;
  60833. }
  60834. if (intensity > 1.0) {
  60835. intensity = 1.0;
  60836. }
  60837. if (this.viewportBorder > 0) {
  60838. globalViewport.x += this.viewportBorder;
  60839. globalViewport.y += this.viewportBorder;
  60840. globalViewport.width -= this.viewportBorder * 2;
  60841. globalViewport.height -= this.viewportBorder * 2;
  60842. this._positionX -= this.viewportBorder;
  60843. this._positionY -= this.viewportBorder;
  60844. }
  60845. // Position
  60846. var centerX = globalViewport.x + globalViewport.width / 2;
  60847. var centerY = globalViewport.y + globalViewport.height / 2;
  60848. var distX = centerX - this._positionX;
  60849. var distY = centerY - this._positionY;
  60850. // Effects
  60851. engine.enableEffect(this._effect);
  60852. engine.setState(false);
  60853. engine.setDepthBuffer(false);
  60854. // VBOs
  60855. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60856. // Flares
  60857. for (var index = 0; index < this.lensFlares.length; index++) {
  60858. var flare = this.lensFlares[index];
  60859. engine.setAlphaMode(flare.alphaMode);
  60860. var x = centerX - (distX * flare.position);
  60861. var y = centerY - (distY * flare.position);
  60862. var cw = flare.size;
  60863. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  60864. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  60865. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  60866. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  60867. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  60868. // Texture
  60869. this._effect.setTexture("textureSampler", flare.texture);
  60870. // Color
  60871. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  60872. // Draw order
  60873. engine.draw(true, 0, 6);
  60874. }
  60875. engine.setDepthBuffer(true);
  60876. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60877. return true;
  60878. };
  60879. LensFlareSystem.prototype.dispose = function () {
  60880. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60881. if (vertexBuffer) {
  60882. vertexBuffer.dispose();
  60883. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60884. }
  60885. if (this._indexBuffer) {
  60886. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60887. this._indexBuffer = null;
  60888. }
  60889. while (this.lensFlares.length) {
  60890. this.lensFlares[0].dispose();
  60891. }
  60892. // Remove from scene
  60893. var index = this._scene.lensFlareSystems.indexOf(this);
  60894. this._scene.lensFlareSystems.splice(index, 1);
  60895. };
  60896. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  60897. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  60898. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  60899. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  60900. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  60901. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  60902. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  60903. var parsedFlare = parsedLensFlareSystem.flares[index];
  60904. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  60905. }
  60906. return lensFlareSystem;
  60907. };
  60908. LensFlareSystem.prototype.serialize = function () {
  60909. var serializationObject = {};
  60910. serializationObject.id = this.id;
  60911. serializationObject.name = this.name;
  60912. serializationObject.emitterId = this.getEmitter().id;
  60913. serializationObject.borderLimit = this.borderLimit;
  60914. serializationObject.flares = [];
  60915. for (var index = 0; index < this.lensFlares.length; index++) {
  60916. var flare = this.lensFlares[index];
  60917. serializationObject.flares.push({
  60918. size: flare.size,
  60919. position: flare.position,
  60920. color: flare.color.asArray(),
  60921. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  60922. });
  60923. }
  60924. return serializationObject;
  60925. };
  60926. return LensFlareSystem;
  60927. }());
  60928. BABYLON.LensFlareSystem = LensFlareSystem;
  60929. })(BABYLON || (BABYLON = {}));
  60930. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  60931. var BABYLON;
  60932. (function (BABYLON) {
  60933. /**
  60934. * This is a holder class for the physics joint created by the physics plugin.
  60935. * It holds a set of functions to control the underlying joint.
  60936. */
  60937. var PhysicsJoint = (function () {
  60938. function PhysicsJoint(type, jointData) {
  60939. this.type = type;
  60940. this.jointData = jointData;
  60941. jointData.nativeParams = jointData.nativeParams || {};
  60942. }
  60943. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  60944. get: function () {
  60945. return this._physicsJoint;
  60946. },
  60947. set: function (newJoint) {
  60948. if (this._physicsJoint) {
  60949. //remove from the wolrd
  60950. }
  60951. this._physicsJoint = newJoint;
  60952. },
  60953. enumerable: true,
  60954. configurable: true
  60955. });
  60956. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  60957. set: function (physicsPlugin) {
  60958. this._physicsPlugin = physicsPlugin;
  60959. },
  60960. enumerable: true,
  60961. configurable: true
  60962. });
  60963. /**
  60964. * Execute a function that is physics-plugin specific.
  60965. * @param {Function} func the function that will be executed.
  60966. * It accepts two parameters: the physics world and the physics joint.
  60967. */
  60968. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  60969. func(this._physicsPlugin.world, this._physicsJoint);
  60970. };
  60971. //TODO check if the native joints are the same
  60972. //Joint Types
  60973. PhysicsJoint.DistanceJoint = 0;
  60974. PhysicsJoint.HingeJoint = 1;
  60975. PhysicsJoint.BallAndSocketJoint = 2;
  60976. PhysicsJoint.WheelJoint = 3;
  60977. PhysicsJoint.SliderJoint = 4;
  60978. //OIMO
  60979. PhysicsJoint.PrismaticJoint = 5;
  60980. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  60981. PhysicsJoint.UniversalJoint = 6;
  60982. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  60983. //Cannon
  60984. //Similar to a Ball-Joint. Different in params
  60985. PhysicsJoint.PointToPointJoint = 8;
  60986. //Cannon only at the moment
  60987. PhysicsJoint.SpringJoint = 9;
  60988. PhysicsJoint.LockJoint = 10;
  60989. return PhysicsJoint;
  60990. }());
  60991. BABYLON.PhysicsJoint = PhysicsJoint;
  60992. /**
  60993. * A class representing a physics distance joint.
  60994. */
  60995. var DistanceJoint = (function (_super) {
  60996. __extends(DistanceJoint, _super);
  60997. function DistanceJoint(jointData) {
  60998. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  60999. }
  61000. /**
  61001. * Update the predefined distance.
  61002. */
  61003. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  61004. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  61005. };
  61006. return DistanceJoint;
  61007. }(PhysicsJoint));
  61008. BABYLON.DistanceJoint = DistanceJoint;
  61009. var MotorEnabledJoint = (function (_super) {
  61010. __extends(MotorEnabledJoint, _super);
  61011. function MotorEnabledJoint(type, jointData) {
  61012. return _super.call(this, type, jointData) || this;
  61013. }
  61014. /**
  61015. * Set the motor values.
  61016. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61017. * @param {number} force the force to apply
  61018. * @param {number} maxForce max force for this motor.
  61019. */
  61020. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  61021. this._physicsPlugin.setMotor(this, force, maxForce);
  61022. };
  61023. /**
  61024. * Set the motor's limits.
  61025. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61026. */
  61027. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61028. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61029. };
  61030. return MotorEnabledJoint;
  61031. }(PhysicsJoint));
  61032. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  61033. /**
  61034. * This class represents a single hinge physics joint
  61035. */
  61036. var HingeJoint = (function (_super) {
  61037. __extends(HingeJoint, _super);
  61038. function HingeJoint(jointData) {
  61039. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  61040. }
  61041. /**
  61042. * Set the motor values.
  61043. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61044. * @param {number} force the force to apply
  61045. * @param {number} maxForce max force for this motor.
  61046. */
  61047. HingeJoint.prototype.setMotor = function (force, maxForce) {
  61048. this._physicsPlugin.setMotor(this, force, maxForce);
  61049. };
  61050. /**
  61051. * Set the motor's limits.
  61052. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61053. */
  61054. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61055. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61056. };
  61057. return HingeJoint;
  61058. }(MotorEnabledJoint));
  61059. BABYLON.HingeJoint = HingeJoint;
  61060. /**
  61061. * This class represents a dual hinge physics joint (same as wheel joint)
  61062. */
  61063. var Hinge2Joint = (function (_super) {
  61064. __extends(Hinge2Joint, _super);
  61065. function Hinge2Joint(jointData) {
  61066. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  61067. }
  61068. /**
  61069. * Set the motor values.
  61070. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61071. * @param {number} force the force to apply
  61072. * @param {number} maxForce max force for this motor.
  61073. * @param {motorIndex} the motor's index, 0 or 1.
  61074. */
  61075. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  61076. if (motorIndex === void 0) { motorIndex = 0; }
  61077. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  61078. };
  61079. /**
  61080. * Set the motor limits.
  61081. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61082. * @param {number} upperLimit the upper limit
  61083. * @param {number} lowerLimit lower limit
  61084. * @param {motorIndex} the motor's index, 0 or 1.
  61085. */
  61086. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  61087. if (motorIndex === void 0) { motorIndex = 0; }
  61088. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  61089. };
  61090. return Hinge2Joint;
  61091. }(MotorEnabledJoint));
  61092. BABYLON.Hinge2Joint = Hinge2Joint;
  61093. })(BABYLON || (BABYLON = {}));
  61094. //# sourceMappingURL=babylon.physicsJoint.js.map
  61095. var BABYLON;
  61096. (function (BABYLON) {
  61097. var PhysicsImpostor = (function () {
  61098. function PhysicsImpostor(object, type, _options, _scene) {
  61099. if (_options === void 0) { _options = { mass: 0 }; }
  61100. var _this = this;
  61101. this.object = object;
  61102. this.type = type;
  61103. this._options = _options;
  61104. this._scene = _scene;
  61105. this._bodyUpdateRequired = false;
  61106. this._onBeforePhysicsStepCallbacks = new Array();
  61107. this._onAfterPhysicsStepCallbacks = new Array();
  61108. this._onPhysicsCollideCallbacks = [];
  61109. this._deltaPosition = BABYLON.Vector3.Zero();
  61110. this._isDisposed = false;
  61111. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  61112. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  61113. /**
  61114. * this function is executed by the physics engine.
  61115. */
  61116. this.beforeStep = function () {
  61117. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  61118. //conjugate deltaRotation
  61119. if (_this._deltaRotationConjugated) {
  61120. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  61121. }
  61122. else {
  61123. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  61124. }
  61125. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  61126. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  61127. func(_this);
  61128. });
  61129. };
  61130. /**
  61131. * this function is executed by the physics engine.
  61132. */
  61133. this.afterStep = function () {
  61134. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  61135. func(_this);
  61136. });
  61137. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  61138. _this.object.position.addInPlace(_this._deltaPosition);
  61139. if (_this._deltaRotation) {
  61140. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  61141. }
  61142. };
  61143. /**
  61144. * Legacy collision detection event support
  61145. */
  61146. this.onCollideEvent = null;
  61147. //event and body object due to cannon's event-based architecture.
  61148. this.onCollide = function (e) {
  61149. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  61150. return;
  61151. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  61152. if (otherImpostor) {
  61153. // Legacy collision detection event support
  61154. if (_this.onCollideEvent) {
  61155. _this.onCollideEvent(_this, otherImpostor);
  61156. }
  61157. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  61158. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  61159. }).forEach(function (obj) {
  61160. obj.callback(_this, otherImpostor);
  61161. });
  61162. }
  61163. };
  61164. //sanity check!
  61165. if (!this.object) {
  61166. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  61167. return;
  61168. }
  61169. //legacy support for old syntax.
  61170. if (!this._scene && object.getScene) {
  61171. this._scene = object.getScene();
  61172. }
  61173. this._physicsEngine = this._scene.getPhysicsEngine();
  61174. if (!this._physicsEngine) {
  61175. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  61176. }
  61177. else {
  61178. //set the object's quaternion, if not set
  61179. if (!this.object.rotationQuaternion) {
  61180. if (this.object.rotation) {
  61181. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  61182. }
  61183. else {
  61184. this.object.rotationQuaternion = new BABYLON.Quaternion();
  61185. }
  61186. }
  61187. //default options params
  61188. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  61189. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  61190. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  61191. this._joints = [];
  61192. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  61193. if (!this.object.parent) {
  61194. this._init();
  61195. }
  61196. else if (this.object.parent.physicsImpostor) {
  61197. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  61198. }
  61199. }
  61200. }
  61201. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  61202. get: function () {
  61203. return this._isDisposed;
  61204. },
  61205. enumerable: true,
  61206. configurable: true
  61207. });
  61208. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  61209. get: function () {
  61210. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  61211. },
  61212. set: function (value) {
  61213. this.setMass(value);
  61214. },
  61215. enumerable: true,
  61216. configurable: true
  61217. });
  61218. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  61219. get: function () {
  61220. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  61221. },
  61222. set: function (value) {
  61223. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  61224. },
  61225. enumerable: true,
  61226. configurable: true
  61227. });
  61228. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  61229. get: function () {
  61230. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  61231. },
  61232. set: function (value) {
  61233. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  61234. },
  61235. enumerable: true,
  61236. configurable: true
  61237. });
  61238. /**
  61239. * This function will completly initialize this impostor.
  61240. * It will create a new body - but only if this mesh has no parent.
  61241. * If it has, this impostor will not be used other than to define the impostor
  61242. * of the child mesh.
  61243. */
  61244. PhysicsImpostor.prototype._init = function () {
  61245. this._physicsEngine.removeImpostor(this);
  61246. this.physicsBody = null;
  61247. this._parent = this._parent || this._getPhysicsParent();
  61248. if (!this.parent) {
  61249. this._physicsEngine.addImpostor(this);
  61250. }
  61251. };
  61252. PhysicsImpostor.prototype._getPhysicsParent = function () {
  61253. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  61254. var parentMesh = this.object.parent;
  61255. return parentMesh.physicsImpostor;
  61256. }
  61257. return;
  61258. };
  61259. /**
  61260. * Should a new body be generated.
  61261. */
  61262. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  61263. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  61264. };
  61265. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  61266. this.forceUpdate();
  61267. };
  61268. /**
  61269. * Force a regeneration of this or the parent's impostor's body.
  61270. * Use under cautious - This will remove all joints already implemented.
  61271. */
  61272. PhysicsImpostor.prototype.forceUpdate = function () {
  61273. this._init();
  61274. if (this.parent) {
  61275. this.parent.forceUpdate();
  61276. }
  61277. };
  61278. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  61279. /*public get mesh(): AbstractMesh {
  61280. return this._mesh;
  61281. }*/
  61282. /**
  61283. * Gets the body that holds this impostor. Either its own, or its parent.
  61284. */
  61285. get: function () {
  61286. return this._parent ? this._parent.physicsBody : this._physicsBody;
  61287. },
  61288. /**
  61289. * Set the physics body. Used mainly by the physics engine/plugin
  61290. */
  61291. set: function (physicsBody) {
  61292. if (this._physicsBody) {
  61293. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  61294. }
  61295. this._physicsBody = physicsBody;
  61296. this.resetUpdateFlags();
  61297. },
  61298. enumerable: true,
  61299. configurable: true
  61300. });
  61301. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  61302. get: function () {
  61303. return this._parent;
  61304. },
  61305. set: function (value) {
  61306. this._parent = value;
  61307. },
  61308. enumerable: true,
  61309. configurable: true
  61310. });
  61311. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  61312. this._bodyUpdateRequired = false;
  61313. };
  61314. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  61315. if (this.object.getBoundingInfo) {
  61316. var q = this.object.rotationQuaternion;
  61317. //reset rotation
  61318. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  61319. //calculate the world matrix with no rotation
  61320. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61321. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  61322. //bring back the rotation
  61323. this.object.rotationQuaternion = q;
  61324. //calculate the world matrix with the new rotation
  61325. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61326. return size;
  61327. }
  61328. else {
  61329. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  61330. }
  61331. };
  61332. PhysicsImpostor.prototype.getObjectCenter = function () {
  61333. if (this.object.getBoundingInfo) {
  61334. return this.object.getBoundingInfo().boundingBox.centerWorld;
  61335. }
  61336. else {
  61337. return this.object.position;
  61338. }
  61339. };
  61340. /**
  61341. * Get a specific parametes from the options parameter.
  61342. */
  61343. PhysicsImpostor.prototype.getParam = function (paramName) {
  61344. return this._options[paramName];
  61345. };
  61346. /**
  61347. * Sets a specific parameter in the options given to the physics plugin
  61348. */
  61349. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  61350. this._options[paramName] = value;
  61351. this._bodyUpdateRequired = true;
  61352. };
  61353. /**
  61354. * Specifically change the body's mass option. Won't recreate the physics body object
  61355. */
  61356. PhysicsImpostor.prototype.setMass = function (mass) {
  61357. if (this.getParam("mass") !== mass) {
  61358. this.setParam("mass", mass);
  61359. }
  61360. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  61361. };
  61362. PhysicsImpostor.prototype.getLinearVelocity = function () {
  61363. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  61364. };
  61365. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  61366. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  61367. };
  61368. PhysicsImpostor.prototype.getAngularVelocity = function () {
  61369. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  61370. };
  61371. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  61372. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  61373. };
  61374. /**
  61375. * Execute a function with the physics plugin native code.
  61376. * Provide a function the will have two variables - the world object and the physics body object.
  61377. */
  61378. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  61379. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  61380. };
  61381. /**
  61382. * Register a function that will be executed before the physics world is stepping forward.
  61383. */
  61384. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  61385. this._onBeforePhysicsStepCallbacks.push(func);
  61386. };
  61387. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  61388. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  61389. if (index > -1) {
  61390. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  61391. }
  61392. else {
  61393. BABYLON.Tools.Warn("Function to remove was not found");
  61394. }
  61395. };
  61396. /**
  61397. * Register a function that will be executed after the physics step
  61398. */
  61399. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  61400. this._onAfterPhysicsStepCallbacks.push(func);
  61401. };
  61402. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  61403. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  61404. if (index > -1) {
  61405. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  61406. }
  61407. else {
  61408. BABYLON.Tools.Warn("Function to remove was not found");
  61409. }
  61410. };
  61411. /**
  61412. * register a function that will be executed when this impostor collides against a different body.
  61413. */
  61414. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  61415. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61416. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  61417. };
  61418. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  61419. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61420. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  61421. if (index > -1) {
  61422. this._onPhysicsCollideCallbacks.splice(index, 1);
  61423. }
  61424. else {
  61425. BABYLON.Tools.Warn("Function to remove was not found");
  61426. }
  61427. };
  61428. /**
  61429. * Apply a force
  61430. */
  61431. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  61432. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  61433. };
  61434. /**
  61435. * Apply an impulse
  61436. */
  61437. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  61438. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  61439. };
  61440. /**
  61441. * A help function to create a joint.
  61442. */
  61443. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  61444. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  61445. this.addJoint(otherImpostor, joint);
  61446. };
  61447. /**
  61448. * Add a joint to this impostor with a different impostor.
  61449. */
  61450. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  61451. this._joints.push({
  61452. otherImpostor: otherImpostor,
  61453. joint: joint
  61454. });
  61455. this._physicsEngine.addJoint(this, otherImpostor, joint);
  61456. };
  61457. /**
  61458. * Will keep this body still, in a sleep mode.
  61459. */
  61460. PhysicsImpostor.prototype.sleep = function () {
  61461. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  61462. };
  61463. /**
  61464. * Wake the body up.
  61465. */
  61466. PhysicsImpostor.prototype.wakeUp = function () {
  61467. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  61468. };
  61469. PhysicsImpostor.prototype.clone = function (newObject) {
  61470. if (!newObject)
  61471. return null;
  61472. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  61473. };
  61474. PhysicsImpostor.prototype.dispose = function () {
  61475. var _this = this;
  61476. //no dispose if no physics engine is available.
  61477. if (!this._physicsEngine) {
  61478. return;
  61479. }
  61480. this._joints.forEach(function (j) {
  61481. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  61482. });
  61483. //dispose the physics body
  61484. this._physicsEngine.removeImpostor(this);
  61485. if (this.parent) {
  61486. this.parent.forceUpdate();
  61487. }
  61488. else {
  61489. /*this._object.getChildMeshes().forEach(function(mesh) {
  61490. if (mesh.physicsImpostor) {
  61491. if (disposeChildren) {
  61492. mesh.physicsImpostor.dispose();
  61493. mesh.physicsImpostor = null;
  61494. }
  61495. }
  61496. })*/
  61497. }
  61498. this._isDisposed = true;
  61499. };
  61500. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  61501. this._deltaPosition.copyFrom(position);
  61502. };
  61503. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  61504. if (!this._deltaRotation) {
  61505. this._deltaRotation = new BABYLON.Quaternion();
  61506. }
  61507. this._deltaRotation.copyFrom(rotation);
  61508. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  61509. };
  61510. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  61511. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  61512. };
  61513. PhysicsImpostor.prototype.getRadius = function () {
  61514. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  61515. };
  61516. /**
  61517. * Sync a bone with this impostor
  61518. * @param bone The bone to sync to the impostor.
  61519. * @param boneMesh The mesh that the bone is influencing.
  61520. * @param jointPivot The pivot of the joint / bone in local space.
  61521. * @param distToJoint Optional distance from the impostor to the joint.
  61522. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61523. */
  61524. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  61525. var tempVec = PhysicsImpostor._tmpVecs[0];
  61526. var mesh = this.object;
  61527. if (adjustRotation) {
  61528. var tempQuat = PhysicsImpostor._tmpQuat;
  61529. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  61530. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  61531. }
  61532. else {
  61533. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  61534. }
  61535. tempVec.x = 0;
  61536. tempVec.y = 0;
  61537. tempVec.z = 0;
  61538. if (jointPivot) {
  61539. tempVec.x = jointPivot.x;
  61540. tempVec.y = jointPivot.y;
  61541. tempVec.z = jointPivot.z;
  61542. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  61543. if (distToJoint === undefined || distToJoint === null) {
  61544. distToJoint = jointPivot.length();
  61545. }
  61546. tempVec.x *= distToJoint;
  61547. tempVec.y *= distToJoint;
  61548. tempVec.z *= distToJoint;
  61549. }
  61550. if (bone.getParent()) {
  61551. tempVec.addInPlace(mesh.getAbsolutePosition());
  61552. bone.setAbsolutePosition(tempVec, boneMesh);
  61553. }
  61554. else {
  61555. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  61556. boneMesh.position.x -= tempVec.x;
  61557. boneMesh.position.y -= tempVec.y;
  61558. boneMesh.position.z -= tempVec.z;
  61559. }
  61560. };
  61561. /**
  61562. * Sync impostor to a bone
  61563. * @param bone The bone that the impostor will be synced to.
  61564. * @param boneMesh The mesh that the bone is influencing.
  61565. * @param jointPivot The pivot of the joint / bone in local space.
  61566. * @param distToJoint Optional distance from the impostor to the joint.
  61567. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61568. * @param boneAxis Optional vector3 axis the bone is aligned with
  61569. */
  61570. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  61571. var mesh = this.object;
  61572. if (adjustRotation) {
  61573. var tempQuat = PhysicsImpostor._tmpQuat;
  61574. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  61575. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  61576. }
  61577. else {
  61578. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  61579. }
  61580. var pos = PhysicsImpostor._tmpVecs[0];
  61581. var boneDir = PhysicsImpostor._tmpVecs[1];
  61582. if (!boneAxis) {
  61583. boneAxis = PhysicsImpostor._tmpVecs[2];
  61584. boneAxis.x = 0;
  61585. boneAxis.y = 1;
  61586. boneAxis.z = 0;
  61587. }
  61588. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  61589. bone.getAbsolutePositionToRef(boneMesh, pos);
  61590. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  61591. distToJoint = jointPivot.length();
  61592. }
  61593. if (distToJoint !== undefined && distToJoint !== null) {
  61594. pos.x += boneDir.x * distToJoint;
  61595. pos.y += boneDir.y * distToJoint;
  61596. pos.z += boneDir.z * distToJoint;
  61597. }
  61598. mesh.setAbsolutePosition(pos);
  61599. };
  61600. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  61601. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  61602. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61603. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  61604. //Impostor types
  61605. PhysicsImpostor.NoImpostor = 0;
  61606. PhysicsImpostor.SphereImpostor = 1;
  61607. PhysicsImpostor.BoxImpostor = 2;
  61608. PhysicsImpostor.PlaneImpostor = 3;
  61609. PhysicsImpostor.MeshImpostor = 4;
  61610. PhysicsImpostor.CylinderImpostor = 7;
  61611. PhysicsImpostor.ParticleImpostor = 8;
  61612. PhysicsImpostor.HeightmapImpostor = 9;
  61613. return PhysicsImpostor;
  61614. }());
  61615. BABYLON.PhysicsImpostor = PhysicsImpostor;
  61616. })(BABYLON || (BABYLON = {}));
  61617. //# sourceMappingURL=babylon.physicsImpostor.js.map
  61618. var BABYLON;
  61619. (function (BABYLON) {
  61620. var PhysicsEngine = (function () {
  61621. function PhysicsEngine(gravity, _physicsPlugin) {
  61622. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  61623. this._physicsPlugin = _physicsPlugin;
  61624. //new methods and parameters
  61625. this._impostors = [];
  61626. this._joints = [];
  61627. if (!this._physicsPlugin.isSupported()) {
  61628. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  61629. + "Please make sure it is included.");
  61630. }
  61631. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  61632. this.setGravity(gravity);
  61633. this.setTimeStep();
  61634. }
  61635. PhysicsEngine.prototype.setGravity = function (gravity) {
  61636. this.gravity = gravity;
  61637. this._physicsPlugin.setGravity(this.gravity);
  61638. };
  61639. /**
  61640. * Set the time step of the physics engine.
  61641. * default is 1/60.
  61642. * To slow it down, enter 1/600 for example.
  61643. * To speed it up, 1/30
  61644. * @param {number} newTimeStep the new timestep to apply to this world.
  61645. */
  61646. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  61647. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  61648. this._physicsPlugin.setTimeStep(newTimeStep);
  61649. };
  61650. /**
  61651. * Get the time step of the physics engine.
  61652. */
  61653. PhysicsEngine.prototype.getTimeStep = function () {
  61654. return this._physicsPlugin.getTimeStep();
  61655. };
  61656. PhysicsEngine.prototype.dispose = function () {
  61657. this._impostors.forEach(function (impostor) {
  61658. impostor.dispose();
  61659. });
  61660. this._physicsPlugin.dispose();
  61661. };
  61662. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  61663. return this._physicsPlugin.name;
  61664. };
  61665. /**
  61666. * Adding a new impostor for the impostor tracking.
  61667. * This will be done by the impostor itself.
  61668. * @param {PhysicsImpostor} impostor the impostor to add
  61669. */
  61670. PhysicsEngine.prototype.addImpostor = function (impostor) {
  61671. impostor.uniqueId = this._impostors.push(impostor);
  61672. //if no parent, generate the body
  61673. if (!impostor.parent) {
  61674. this._physicsPlugin.generatePhysicsBody(impostor);
  61675. }
  61676. };
  61677. /**
  61678. * Remove an impostor from the engine.
  61679. * This impostor and its mesh will not longer be updated by the physics engine.
  61680. * @param {PhysicsImpostor} impostor the impostor to remove
  61681. */
  61682. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  61683. var index = this._impostors.indexOf(impostor);
  61684. if (index > -1) {
  61685. var removed = this._impostors.splice(index, 1);
  61686. //Is it needed?
  61687. if (removed.length) {
  61688. //this will also remove it from the world.
  61689. removed[0].physicsBody = null;
  61690. }
  61691. }
  61692. };
  61693. /**
  61694. * Add a joint to the physics engine
  61695. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  61696. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  61697. * @param {PhysicsJoint} the joint that will connect both impostors.
  61698. */
  61699. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  61700. var impostorJoint = {
  61701. mainImpostor: mainImpostor,
  61702. connectedImpostor: connectedImpostor,
  61703. joint: joint
  61704. };
  61705. joint.physicsPlugin = this._physicsPlugin;
  61706. this._joints.push(impostorJoint);
  61707. this._physicsPlugin.generateJoint(impostorJoint);
  61708. };
  61709. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  61710. var matchingJoints = this._joints.filter(function (impostorJoint) {
  61711. return (impostorJoint.connectedImpostor === connectedImpostor
  61712. && impostorJoint.joint === joint
  61713. && impostorJoint.mainImpostor === mainImpostor);
  61714. });
  61715. if (matchingJoints.length) {
  61716. this._physicsPlugin.removeJoint(matchingJoints[0]);
  61717. //TODO remove it from the list as well
  61718. }
  61719. };
  61720. /**
  61721. * Called by the scene. no need to call it.
  61722. */
  61723. PhysicsEngine.prototype._step = function (delta) {
  61724. var _this = this;
  61725. //check if any mesh has no body / requires an update
  61726. this._impostors.forEach(function (impostor) {
  61727. if (impostor.isBodyInitRequired()) {
  61728. _this._physicsPlugin.generatePhysicsBody(impostor);
  61729. }
  61730. });
  61731. if (delta > 0.1) {
  61732. delta = 0.1;
  61733. }
  61734. else if (delta <= 0) {
  61735. delta = 1.0 / 60.0;
  61736. }
  61737. this._physicsPlugin.executeStep(delta, this._impostors);
  61738. };
  61739. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  61740. return this._physicsPlugin;
  61741. };
  61742. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  61743. for (var i = 0; i < this._impostors.length; ++i) {
  61744. if (this._impostors[i].object === object) {
  61745. return this._impostors[i];
  61746. }
  61747. }
  61748. };
  61749. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  61750. for (var i = 0; i < this._impostors.length; ++i) {
  61751. if (this._impostors[i].physicsBody === body) {
  61752. return this._impostors[i];
  61753. }
  61754. }
  61755. };
  61756. // Statics
  61757. PhysicsEngine.Epsilon = 0.001;
  61758. return PhysicsEngine;
  61759. }());
  61760. BABYLON.PhysicsEngine = PhysicsEngine;
  61761. })(BABYLON || (BABYLON = {}));
  61762. //# sourceMappingURL=babylon.physicsEngine.js.map
  61763. var BABYLON;
  61764. (function (BABYLON) {
  61765. var CannonJSPlugin = (function () {
  61766. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  61767. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  61768. if (iterations === void 0) { iterations = 10; }
  61769. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  61770. this.name = "CannonJSPlugin";
  61771. this._physicsMaterials = [];
  61772. this._fixedTimeStep = 1 / 60;
  61773. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61774. this._currentCollisionGroup = 2;
  61775. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  61776. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  61777. this._tmpPosition = BABYLON.Vector3.Zero();
  61778. this._tmpQuaternion = new BABYLON.Quaternion();
  61779. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  61780. this._tmpDeltaRotation = new BABYLON.Quaternion();
  61781. this._tmpUnityRotation = new BABYLON.Quaternion();
  61782. if (!this.isSupported()) {
  61783. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  61784. return;
  61785. }
  61786. this.world = new CANNON.World();
  61787. this.world.broadphase = new CANNON.NaiveBroadphase();
  61788. this.world.solver.iterations = iterations;
  61789. }
  61790. CannonJSPlugin.prototype.setGravity = function (gravity) {
  61791. this.world.gravity.copy(gravity);
  61792. };
  61793. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  61794. this._fixedTimeStep = timeStep;
  61795. };
  61796. CannonJSPlugin.prototype.getTimeStep = function () {
  61797. return this._fixedTimeStep;
  61798. };
  61799. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  61800. // Delta is in seconds, should be provided in milliseconds
  61801. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  61802. };
  61803. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61804. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  61805. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  61806. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  61807. };
  61808. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61809. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  61810. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  61811. impostor.physicsBody.applyForce(impulse, worldPoint);
  61812. };
  61813. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61814. //parent-child relationship. Does this impostor has a parent impostor?
  61815. if (impostor.parent) {
  61816. if (impostor.physicsBody) {
  61817. this.removePhysicsBody(impostor);
  61818. //TODO is that needed?
  61819. impostor.forceUpdate();
  61820. }
  61821. return;
  61822. }
  61823. //should a new body be created for this impostor?
  61824. if (impostor.isBodyInitRequired()) {
  61825. var shape = this._createShape(impostor);
  61826. //unregister events, if body is being changed
  61827. var oldBody = impostor.physicsBody;
  61828. if (oldBody) {
  61829. this.removePhysicsBody(impostor);
  61830. }
  61831. //create the body and material
  61832. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  61833. var bodyCreationObject = {
  61834. mass: impostor.getParam("mass"),
  61835. material: material
  61836. };
  61837. // A simple extend, in case native options were used.
  61838. var nativeOptions = impostor.getParam("nativeOptions");
  61839. for (var key in nativeOptions) {
  61840. if (nativeOptions.hasOwnProperty(key)) {
  61841. bodyCreationObject[key] = nativeOptions[key];
  61842. }
  61843. }
  61844. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  61845. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  61846. this.world.addEventListener("preStep", impostor.beforeStep);
  61847. this.world.addEventListener("postStep", impostor.afterStep);
  61848. impostor.physicsBody.addShape(shape);
  61849. this.world.add(impostor.physicsBody);
  61850. //try to keep the body moving in the right direction by taking old properties.
  61851. //Should be tested!
  61852. if (oldBody) {
  61853. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  61854. impostor.physicsBody[param].copy(oldBody[param]);
  61855. });
  61856. }
  61857. this._processChildMeshes(impostor);
  61858. }
  61859. //now update the body's transformation
  61860. this._updatePhysicsBodyTransformation(impostor);
  61861. };
  61862. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  61863. var _this = this;
  61864. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  61865. if (meshChildren.length) {
  61866. var processMesh = function (localPosition, mesh) {
  61867. var childImpostor = mesh.getPhysicsImpostor();
  61868. if (childImpostor) {
  61869. var parent = childImpostor.parent;
  61870. if (parent !== mainImpostor) {
  61871. var localPosition = mesh.position;
  61872. if (childImpostor.physicsBody) {
  61873. _this.removePhysicsBody(childImpostor);
  61874. childImpostor.physicsBody = null;
  61875. }
  61876. childImpostor.parent = mainImpostor;
  61877. childImpostor.resetUpdateFlags();
  61878. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  61879. //Add the mass of the children.
  61880. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  61881. }
  61882. }
  61883. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  61884. };
  61885. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  61886. }
  61887. };
  61888. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61889. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  61890. this.world.removeEventListener("preStep", impostor.beforeStep);
  61891. this.world.removeEventListener("postStep", impostor.afterStep);
  61892. this.world.remove(impostor.physicsBody);
  61893. };
  61894. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61895. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61896. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61897. if (!mainBody || !connectedBody) {
  61898. return;
  61899. }
  61900. var constraint;
  61901. var jointData = impostorJoint.joint.jointData;
  61902. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61903. var constraintData = {
  61904. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  61905. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  61906. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  61907. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  61908. maxForce: jointData.nativeParams.maxForce,
  61909. collideConnected: !!jointData.collision
  61910. };
  61911. switch (impostorJoint.joint.type) {
  61912. case BABYLON.PhysicsJoint.HingeJoint:
  61913. case BABYLON.PhysicsJoint.Hinge2Joint:
  61914. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  61915. break;
  61916. case BABYLON.PhysicsJoint.DistanceJoint:
  61917. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  61918. break;
  61919. case BABYLON.PhysicsJoint.SpringJoint:
  61920. var springData = jointData;
  61921. constraint = new CANNON.Spring(mainBody, connectedBody, {
  61922. restLength: springData.length,
  61923. stiffness: springData.stiffness,
  61924. damping: springData.damping,
  61925. localAnchorA: constraintData.pivotA,
  61926. localAnchorB: constraintData.pivotB
  61927. });
  61928. break;
  61929. case BABYLON.PhysicsJoint.LockJoint:
  61930. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  61931. break;
  61932. case BABYLON.PhysicsJoint.PointToPointJoint:
  61933. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61934. default:
  61935. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  61936. break;
  61937. }
  61938. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  61939. constraint.collideConnected = !!jointData.collision;
  61940. impostorJoint.joint.physicsJoint = constraint;
  61941. //don't add spring as constraint, as it is not one.
  61942. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  61943. this.world.addConstraint(constraint);
  61944. }
  61945. else {
  61946. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  61947. constraint.applyForce();
  61948. });
  61949. }
  61950. };
  61951. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61952. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  61953. };
  61954. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  61955. var index;
  61956. var mat;
  61957. for (index = 0; index < this._physicsMaterials.length; index++) {
  61958. mat = this._physicsMaterials[index];
  61959. if (mat.friction === friction && mat.restitution === restitution) {
  61960. return mat;
  61961. }
  61962. }
  61963. var currentMat = new CANNON.Material(name);
  61964. currentMat.friction = friction;
  61965. currentMat.restitution = restitution;
  61966. this._physicsMaterials.push(currentMat);
  61967. return currentMat;
  61968. };
  61969. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  61970. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  61971. };
  61972. CannonJSPlugin.prototype._createShape = function (impostor) {
  61973. var object = impostor.object;
  61974. var returnValue;
  61975. var extendSize = impostor.getObjectExtendSize();
  61976. switch (impostor.type) {
  61977. case BABYLON.PhysicsImpostor.SphereImpostor:
  61978. var radiusX = extendSize.x;
  61979. var radiusY = extendSize.y;
  61980. var radiusZ = extendSize.z;
  61981. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  61982. break;
  61983. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  61984. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61985. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  61986. break;
  61987. case BABYLON.PhysicsImpostor.BoxImpostor:
  61988. var box = extendSize.scale(0.5);
  61989. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  61990. break;
  61991. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61992. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  61993. returnValue = new CANNON.Plane();
  61994. break;
  61995. case BABYLON.PhysicsImpostor.MeshImpostor:
  61996. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  61997. var rawFaces = object.getIndices ? object.getIndices() : [];
  61998. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  61999. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  62000. break;
  62001. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  62002. returnValue = this._createHeightmap(object);
  62003. break;
  62004. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62005. returnValue = new CANNON.Particle();
  62006. break;
  62007. }
  62008. return returnValue;
  62009. };
  62010. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  62011. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62012. var matrix = [];
  62013. //For now pointDepth will not be used and will be automatically calculated.
  62014. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  62015. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  62016. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62017. var elementSize = dim * 2 / arraySize;
  62018. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62019. for (var i = 0; i < pos.length; i = i + 3) {
  62020. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  62021. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  62022. var y = pos[i + 1] + minY;
  62023. if (!matrix[x]) {
  62024. matrix[x] = [];
  62025. }
  62026. if (!matrix[x][z]) {
  62027. matrix[x][z] = y;
  62028. }
  62029. matrix[x][z] = Math.max(y, matrix[x][z]);
  62030. }
  62031. for (var x = 0; x <= arraySize; ++x) {
  62032. if (!matrix[x]) {
  62033. var loc = 1;
  62034. while (!matrix[(x + loc) % arraySize]) {
  62035. loc++;
  62036. }
  62037. matrix[x] = matrix[(x + loc) % arraySize].slice();
  62038. //console.log("missing x", x);
  62039. }
  62040. for (var z = 0; z <= arraySize; ++z) {
  62041. if (!matrix[x][z]) {
  62042. var loc = 1;
  62043. var newValue;
  62044. while (newValue === undefined) {
  62045. newValue = matrix[x][(z + loc++) % arraySize];
  62046. }
  62047. matrix[x][z] = newValue;
  62048. }
  62049. }
  62050. }
  62051. var shape = new CANNON.Heightfield(matrix, {
  62052. elementSize: elementSize
  62053. });
  62054. //For future reference, needed for body transformation
  62055. shape.minY = minY;
  62056. return shape;
  62057. };
  62058. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  62059. var object = impostor.object;
  62060. //make sure it is updated...
  62061. object.computeWorldMatrix && object.computeWorldMatrix(true);
  62062. // The delta between the mesh position and the mesh bounding box center
  62063. var center = impostor.getObjectCenter();
  62064. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  62065. this._tmpPosition.copyFrom(center);
  62066. var quaternion = object.rotationQuaternion;
  62067. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  62068. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  62069. //-90 DEG in X, precalculated
  62070. quaternion = quaternion.multiply(this._minus90X);
  62071. //Invert! (Precalculated, 90 deg in X)
  62072. //No need to clone. this will never change.
  62073. impostor.setDeltaRotation(this._plus90X);
  62074. }
  62075. //If it is a heightfield, if should be centered.
  62076. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  62077. var mesh = object;
  62078. //calculate the correct body position:
  62079. var rotationQuaternion = mesh.rotationQuaternion;
  62080. mesh.rotationQuaternion = this._tmpUnityRotation;
  62081. mesh.computeWorldMatrix(true);
  62082. //get original center with no rotation
  62083. var c = center.clone();
  62084. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  62085. //rotation is back
  62086. mesh.rotationQuaternion = rotationQuaternion;
  62087. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  62088. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62089. mesh.setPivotMatrix(p);
  62090. mesh.computeWorldMatrix(true);
  62091. //calculate the translation
  62092. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  62093. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  62094. //add it inverted to the delta
  62095. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  62096. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62097. mesh.setPivotMatrix(oldPivot);
  62098. mesh.computeWorldMatrix(true);
  62099. }
  62100. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  62101. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  62102. this._tmpPosition.copyFrom(object.position);
  62103. }
  62104. impostor.setDeltaPosition(this._tmpDeltaPosition);
  62105. //Now update the impostor object
  62106. impostor.physicsBody.position.copy(this._tmpPosition);
  62107. impostor.physicsBody.quaternion.copy(quaternion);
  62108. };
  62109. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62110. impostor.object.position.copyFrom(impostor.physicsBody.position);
  62111. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  62112. };
  62113. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62114. impostor.physicsBody.position.copy(newPosition);
  62115. impostor.physicsBody.quaternion.copy(newRotation);
  62116. };
  62117. CannonJSPlugin.prototype.isSupported = function () {
  62118. return window.CANNON !== undefined;
  62119. };
  62120. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62121. impostor.physicsBody.velocity.copy(velocity);
  62122. };
  62123. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62124. impostor.physicsBody.angularVelocity.copy(velocity);
  62125. };
  62126. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62127. var v = impostor.physicsBody.velocity;
  62128. if (!v)
  62129. return null;
  62130. return new BABYLON.Vector3(v.x, v.y, v.z);
  62131. };
  62132. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62133. var v = impostor.physicsBody.angularVelocity;
  62134. if (!v)
  62135. return null;
  62136. return new BABYLON.Vector3(v.x, v.y, v.z);
  62137. };
  62138. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62139. impostor.physicsBody.mass = mass;
  62140. impostor.physicsBody.updateMassProperties();
  62141. };
  62142. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  62143. return impostor.physicsBody.mass;
  62144. };
  62145. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  62146. return impostor.physicsBody.material.friction;
  62147. };
  62148. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62149. impostor.physicsBody.material.friction = friction;
  62150. };
  62151. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62152. return impostor.physicsBody.material.restitution;
  62153. };
  62154. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62155. impostor.physicsBody.material.restitution = restitution;
  62156. };
  62157. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  62158. impostor.physicsBody.sleep();
  62159. };
  62160. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  62161. impostor.physicsBody.wakeUp();
  62162. };
  62163. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62164. joint.physicsJoint.distance = maxDistance;
  62165. };
  62166. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  62167. if (!motorIndex) {
  62168. joint.physicsJoint.enableMotor();
  62169. }
  62170. };
  62171. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  62172. if (!motorIndex) {
  62173. joint.physicsJoint.disableMotor();
  62174. }
  62175. };
  62176. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62177. if (!motorIndex) {
  62178. joint.physicsJoint.enableMotor();
  62179. joint.physicsJoint.setMotorSpeed(speed);
  62180. if (maxForce) {
  62181. this.setLimit(joint, maxForce);
  62182. }
  62183. }
  62184. };
  62185. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  62186. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  62187. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  62188. };
  62189. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62190. var body = impostor.physicsBody;
  62191. mesh.position.x = body.position.x;
  62192. mesh.position.y = body.position.y;
  62193. mesh.position.z = body.position.z;
  62194. mesh.rotationQuaternion.x = body.quaternion.x;
  62195. mesh.rotationQuaternion.y = body.quaternion.y;
  62196. mesh.rotationQuaternion.z = body.quaternion.z;
  62197. mesh.rotationQuaternion.w = body.quaternion.w;
  62198. };
  62199. CannonJSPlugin.prototype.getRadius = function (impostor) {
  62200. var shape = impostor.physicsBody.shapes[0];
  62201. return shape.boundingSphereRadius;
  62202. };
  62203. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62204. var shape = impostor.physicsBody.shapes[0];
  62205. result.x = shape.halfExtents.x * 2;
  62206. result.y = shape.halfExtents.y * 2;
  62207. result.z = shape.halfExtents.z * 2;
  62208. };
  62209. CannonJSPlugin.prototype.dispose = function () {
  62210. };
  62211. return CannonJSPlugin;
  62212. }());
  62213. BABYLON.CannonJSPlugin = CannonJSPlugin;
  62214. })(BABYLON || (BABYLON = {}));
  62215. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  62216. var BABYLON;
  62217. (function (BABYLON) {
  62218. var OimoJSPlugin = (function () {
  62219. function OimoJSPlugin(iterations) {
  62220. this.name = "OimoJSPlugin";
  62221. this._tmpImpostorsArray = [];
  62222. this._tmpPositionVector = BABYLON.Vector3.Zero();
  62223. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  62224. this.world.worldscale(1);
  62225. this.world.clear();
  62226. //making sure no stats are calculated
  62227. this.world.isNoStat = true;
  62228. }
  62229. OimoJSPlugin.prototype.setGravity = function (gravity) {
  62230. this.world.gravity.copy(gravity);
  62231. };
  62232. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  62233. this.world.timeStep = timeStep;
  62234. };
  62235. OimoJSPlugin.prototype.getTimeStep = function () {
  62236. return this.world.timeStep;
  62237. };
  62238. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  62239. var _this = this;
  62240. impostors.forEach(function (impostor) {
  62241. impostor.beforeStep();
  62242. });
  62243. this.world.step();
  62244. impostors.forEach(function (impostor) {
  62245. impostor.afterStep();
  62246. //update the ordered impostors array
  62247. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  62248. });
  62249. //check for collisions
  62250. var contact = this.world.contacts;
  62251. while (contact !== null) {
  62252. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  62253. contact = contact.next;
  62254. continue;
  62255. }
  62256. //is this body colliding with any other? get the impostor
  62257. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  62258. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  62259. if (!mainImpostor || !collidingImpostor) {
  62260. contact = contact.next;
  62261. continue;
  62262. }
  62263. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  62264. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  62265. contact = contact.next;
  62266. }
  62267. };
  62268. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62269. var mass = impostor.physicsBody.massInfo.mass;
  62270. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  62271. };
  62272. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62273. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  62274. this.applyImpulse(impostor, force, contactPoint);
  62275. };
  62276. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62277. var _this = this;
  62278. //parent-child relationship. Does this impostor has a parent impostor?
  62279. if (impostor.parent) {
  62280. if (impostor.physicsBody) {
  62281. this.removePhysicsBody(impostor);
  62282. //TODO is that needed?
  62283. impostor.forceUpdate();
  62284. }
  62285. return;
  62286. }
  62287. if (impostor.isBodyInitRequired()) {
  62288. var bodyConfig = {
  62289. name: impostor.uniqueId,
  62290. //Oimo must have mass, also for static objects.
  62291. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  62292. size: [],
  62293. type: [],
  62294. pos: [],
  62295. rot: [],
  62296. move: impostor.getParam("mass") !== 0,
  62297. //Supporting older versions of Oimo
  62298. world: this.world
  62299. };
  62300. var impostors = [impostor];
  62301. var addToArray = function (parent) {
  62302. if (!parent.getChildMeshes)
  62303. return;
  62304. parent.getChildMeshes().forEach(function (m) {
  62305. if (m.physicsImpostor) {
  62306. impostors.push(m.physicsImpostor);
  62307. m.physicsImpostor._init();
  62308. }
  62309. });
  62310. };
  62311. addToArray(impostor.object);
  62312. var checkWithEpsilon_1 = function (value) {
  62313. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  62314. };
  62315. impostors.forEach(function (i) {
  62316. //get the correct bounding box
  62317. var oldQuaternion = i.object.rotationQuaternion;
  62318. var rot = new OIMO.Euler().setFromQuaternion({
  62319. x: impostor.object.rotationQuaternion.x,
  62320. y: impostor.object.rotationQuaternion.y,
  62321. z: impostor.object.rotationQuaternion.z,
  62322. s: impostor.object.rotationQuaternion.w
  62323. });
  62324. var extendSize = i.getObjectExtendSize();
  62325. if (i === impostor) {
  62326. var center = impostor.getObjectCenter();
  62327. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  62328. //Can also use Array.prototype.push.apply
  62329. bodyConfig.pos.push(center.x);
  62330. bodyConfig.pos.push(center.y);
  62331. bodyConfig.pos.push(center.z);
  62332. //tmp solution
  62333. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  62334. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  62335. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  62336. }
  62337. else {
  62338. bodyConfig.pos.push(i.object.position.x);
  62339. bodyConfig.pos.push(i.object.position.y);
  62340. bodyConfig.pos.push(i.object.position.z);
  62341. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  62342. bodyConfig.rot.push(0);
  62343. bodyConfig.rot.push(0);
  62344. bodyConfig.rot.push(0);
  62345. }
  62346. // register mesh
  62347. switch (i.type) {
  62348. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62349. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  62350. case BABYLON.PhysicsImpostor.SphereImpostor:
  62351. var radiusX = extendSize.x;
  62352. var radiusY = extendSize.y;
  62353. var radiusZ = extendSize.z;
  62354. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  62355. bodyConfig.type.push('sphere');
  62356. //due to the way oimo works with compounds, add 3 times
  62357. bodyConfig.size.push(size);
  62358. bodyConfig.size.push(size);
  62359. bodyConfig.size.push(size);
  62360. break;
  62361. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62362. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  62363. var sizeY = checkWithEpsilon_1(extendSize.y);
  62364. bodyConfig.type.push('cylinder');
  62365. bodyConfig.size.push(sizeX);
  62366. bodyConfig.size.push(sizeY);
  62367. //due to the way oimo works with compounds, add one more value.
  62368. bodyConfig.size.push(sizeY);
  62369. break;
  62370. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62371. case BABYLON.PhysicsImpostor.BoxImpostor:
  62372. default:
  62373. var sizeX = checkWithEpsilon_1(extendSize.x);
  62374. var sizeY = checkWithEpsilon_1(extendSize.y);
  62375. var sizeZ = checkWithEpsilon_1(extendSize.z);
  62376. bodyConfig.type.push('box');
  62377. bodyConfig.size.push(sizeX);
  62378. bodyConfig.size.push(sizeY);
  62379. bodyConfig.size.push(sizeZ);
  62380. break;
  62381. }
  62382. //actually not needed, but hey...
  62383. i.object.rotationQuaternion = oldQuaternion;
  62384. });
  62385. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  62386. }
  62387. else {
  62388. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  62389. }
  62390. impostor.setDeltaPosition(this._tmpPositionVector);
  62391. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  62392. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  62393. };
  62394. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62395. //impostor.physicsBody.dispose();
  62396. //Same as : (older oimo versions)
  62397. this.world.removeRigidBody(impostor.physicsBody);
  62398. };
  62399. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62400. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62401. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62402. if (!mainBody || !connectedBody) {
  62403. return;
  62404. }
  62405. var jointData = impostorJoint.joint.jointData;
  62406. var options = jointData.nativeParams || {};
  62407. var type;
  62408. var nativeJointData = {
  62409. body1: mainBody,
  62410. body2: connectedBody,
  62411. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  62412. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  62413. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  62414. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  62415. min: options.min,
  62416. max: options.max,
  62417. collision: options.collision || jointData.collision,
  62418. spring: options.spring,
  62419. //supporting older version of Oimo
  62420. world: this.world
  62421. };
  62422. switch (impostorJoint.joint.type) {
  62423. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62424. type = "jointBall";
  62425. break;
  62426. case BABYLON.PhysicsJoint.SpringJoint:
  62427. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  62428. var springData = jointData;
  62429. nativeJointData.min = springData.length || nativeJointData.min;
  62430. //Max should also be set, just make sure it is at least min
  62431. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  62432. case BABYLON.PhysicsJoint.DistanceJoint:
  62433. type = "jointDistance";
  62434. nativeJointData.max = jointData.maxDistance;
  62435. break;
  62436. case BABYLON.PhysicsJoint.PrismaticJoint:
  62437. type = "jointPrisme";
  62438. break;
  62439. case BABYLON.PhysicsJoint.SliderJoint:
  62440. type = "jointSlide";
  62441. break;
  62442. case BABYLON.PhysicsJoint.WheelJoint:
  62443. type = "jointWheel";
  62444. break;
  62445. case BABYLON.PhysicsJoint.HingeJoint:
  62446. default:
  62447. type = "jointHinge";
  62448. break;
  62449. }
  62450. nativeJointData.type = type;
  62451. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  62452. };
  62453. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62454. //Bug in Oimo prevents us from disposing a joint in the playground
  62455. //joint.joint.physicsJoint.dispose();
  62456. //So we will bruteforce it!
  62457. try {
  62458. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  62459. }
  62460. catch (e) {
  62461. BABYLON.Tools.Warn(e);
  62462. }
  62463. };
  62464. OimoJSPlugin.prototype.isSupported = function () {
  62465. return OIMO !== undefined;
  62466. };
  62467. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62468. if (!impostor.physicsBody.sleeping) {
  62469. //TODO check that
  62470. if (impostor.physicsBody.shapes.next) {
  62471. var parentShape = this._getLastShape(impostor.physicsBody);
  62472. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  62473. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  62474. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  62475. }
  62476. else {
  62477. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  62478. }
  62479. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  62480. impostor.object.rotationQuaternion.normalize();
  62481. }
  62482. };
  62483. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62484. var body = impostor.physicsBody;
  62485. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  62486. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  62487. body.syncShapes();
  62488. body.awake();
  62489. };
  62490. OimoJSPlugin.prototype._getLastShape = function (body) {
  62491. var lastShape = body.shapes;
  62492. while (lastShape.next) {
  62493. lastShape = lastShape.next;
  62494. }
  62495. return lastShape;
  62496. };
  62497. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62498. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  62499. };
  62500. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62501. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  62502. };
  62503. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62504. var v = impostor.physicsBody.linearVelocity;
  62505. if (!v)
  62506. return null;
  62507. return new BABYLON.Vector3(v.x, v.y, v.z);
  62508. };
  62509. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62510. var v = impostor.physicsBody.angularVelocity;
  62511. if (!v)
  62512. return null;
  62513. return new BABYLON.Vector3(v.x, v.y, v.z);
  62514. };
  62515. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62516. var staticBody = mass === 0;
  62517. //this will actually set the body's density and not its mass.
  62518. //But this is how oimo treats the mass variable.
  62519. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  62520. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  62521. };
  62522. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  62523. return impostor.physicsBody.shapes.density;
  62524. };
  62525. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  62526. return impostor.physicsBody.shapes.friction;
  62527. };
  62528. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62529. impostor.physicsBody.shapes.friction = friction;
  62530. };
  62531. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62532. return impostor.physicsBody.shapes.restitution;
  62533. };
  62534. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62535. impostor.physicsBody.shapes.restitution = restitution;
  62536. };
  62537. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  62538. impostor.physicsBody.sleep();
  62539. };
  62540. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  62541. impostor.physicsBody.awake();
  62542. };
  62543. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62544. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  62545. if (minDistance !== void 0) {
  62546. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  62547. }
  62548. };
  62549. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62550. //TODO separate rotational and transational motors.
  62551. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62552. if (motor) {
  62553. motor.setMotor(speed, maxForce);
  62554. }
  62555. };
  62556. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  62557. //TODO separate rotational and transational motors.
  62558. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62559. if (motor) {
  62560. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  62561. }
  62562. };
  62563. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62564. var body = impostor.physicsBody;
  62565. mesh.position.x = body.position.x;
  62566. mesh.position.y = body.position.y;
  62567. mesh.position.z = body.position.z;
  62568. mesh.rotationQuaternion.x = body.orientation.x;
  62569. mesh.rotationQuaternion.y = body.orientation.y;
  62570. mesh.rotationQuaternion.z = body.orientation.z;
  62571. mesh.rotationQuaternion.w = body.orientation.s;
  62572. };
  62573. OimoJSPlugin.prototype.getRadius = function (impostor) {
  62574. return impostor.physicsBody.shapes.radius;
  62575. };
  62576. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62577. var shape = impostor.physicsBody.shapes;
  62578. result.x = shape.halfWidth * 2;
  62579. result.y = shape.halfHeight * 2;
  62580. result.z = shape.halfDepth * 2;
  62581. };
  62582. OimoJSPlugin.prototype.dispose = function () {
  62583. this.world.clear();
  62584. };
  62585. return OimoJSPlugin;
  62586. }());
  62587. BABYLON.OimoJSPlugin = OimoJSPlugin;
  62588. })(BABYLON || (BABYLON = {}));
  62589. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  62590. var BABYLON;
  62591. (function (BABYLON) {
  62592. var Internals;
  62593. (function (Internals) {
  62594. /*
  62595. * Based on jsTGALoader - Javascript loader for TGA file
  62596. * By Vincent Thibault
  62597. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  62598. */
  62599. var TGATools = (function () {
  62600. function TGATools() {
  62601. }
  62602. TGATools.GetTGAHeader = function (data) {
  62603. var offset = 0;
  62604. var header = {
  62605. id_length: data[offset++],
  62606. colormap_type: data[offset++],
  62607. image_type: data[offset++],
  62608. colormap_index: data[offset++] | data[offset++] << 8,
  62609. colormap_length: data[offset++] | data[offset++] << 8,
  62610. colormap_size: data[offset++],
  62611. origin: [
  62612. data[offset++] | data[offset++] << 8,
  62613. data[offset++] | data[offset++] << 8
  62614. ],
  62615. width: data[offset++] | data[offset++] << 8,
  62616. height: data[offset++] | data[offset++] << 8,
  62617. pixel_size: data[offset++],
  62618. flags: data[offset++]
  62619. };
  62620. return header;
  62621. };
  62622. TGATools.UploadContent = function (gl, data) {
  62623. // Not enough data to contain header ?
  62624. if (data.length < 19) {
  62625. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  62626. return;
  62627. }
  62628. // Read Header
  62629. var offset = 18;
  62630. var header = TGATools.GetTGAHeader(data);
  62631. // Assume it's a valid Targa file.
  62632. if (header.id_length + offset > data.length) {
  62633. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  62634. return;
  62635. }
  62636. // Skip not needed data
  62637. offset += header.id_length;
  62638. var use_rle = false;
  62639. var use_pal = false;
  62640. var use_rgb = false;
  62641. var use_grey = false;
  62642. // Get some informations.
  62643. switch (header.image_type) {
  62644. case TGATools._TYPE_RLE_INDEXED:
  62645. use_rle = true;
  62646. case TGATools._TYPE_INDEXED:
  62647. use_pal = true;
  62648. break;
  62649. case TGATools._TYPE_RLE_RGB:
  62650. use_rle = true;
  62651. case TGATools._TYPE_RGB:
  62652. use_rgb = true;
  62653. break;
  62654. case TGATools._TYPE_RLE_GREY:
  62655. use_rle = true;
  62656. case TGATools._TYPE_GREY:
  62657. use_grey = true;
  62658. break;
  62659. }
  62660. var pixel_data;
  62661. var numAlphaBits = header.flags & 0xf;
  62662. var pixel_size = header.pixel_size >> 3;
  62663. var pixel_total = header.width * header.height * pixel_size;
  62664. // Read palettes
  62665. var palettes;
  62666. if (use_pal) {
  62667. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  62668. }
  62669. // Read LRE
  62670. if (use_rle) {
  62671. pixel_data = new Uint8Array(pixel_total);
  62672. var c, count, i;
  62673. var localOffset = 0;
  62674. var pixels = new Uint8Array(pixel_size);
  62675. while (offset < pixel_total && localOffset < pixel_total) {
  62676. c = data[offset++];
  62677. count = (c & 0x7f) + 1;
  62678. // RLE pixels
  62679. if (c & 0x80) {
  62680. // Bind pixel tmp array
  62681. for (i = 0; i < pixel_size; ++i) {
  62682. pixels[i] = data[offset++];
  62683. }
  62684. // Copy pixel array
  62685. for (i = 0; i < count; ++i) {
  62686. pixel_data.set(pixels, localOffset + i * pixel_size);
  62687. }
  62688. localOffset += pixel_size * count;
  62689. }
  62690. else {
  62691. count *= pixel_size;
  62692. for (i = 0; i < count; ++i) {
  62693. pixel_data[localOffset + i] = data[offset++];
  62694. }
  62695. localOffset += count;
  62696. }
  62697. }
  62698. }
  62699. else {
  62700. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  62701. }
  62702. // Load to texture
  62703. var x_start, y_start, x_step, y_step, y_end, x_end;
  62704. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  62705. default:
  62706. case TGATools._ORIGIN_UL:
  62707. x_start = 0;
  62708. x_step = 1;
  62709. x_end = header.width;
  62710. y_start = 0;
  62711. y_step = 1;
  62712. y_end = header.height;
  62713. break;
  62714. case TGATools._ORIGIN_BL:
  62715. x_start = 0;
  62716. x_step = 1;
  62717. x_end = header.width;
  62718. y_start = header.height - 1;
  62719. y_step = -1;
  62720. y_end = -1;
  62721. break;
  62722. case TGATools._ORIGIN_UR:
  62723. x_start = header.width - 1;
  62724. x_step = -1;
  62725. x_end = -1;
  62726. y_start = 0;
  62727. y_step = 1;
  62728. y_end = header.height;
  62729. break;
  62730. case TGATools._ORIGIN_BR:
  62731. x_start = header.width - 1;
  62732. x_step = -1;
  62733. x_end = -1;
  62734. y_start = header.height - 1;
  62735. y_step = -1;
  62736. y_end = -1;
  62737. break;
  62738. }
  62739. // Load the specify method
  62740. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  62741. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  62742. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  62743. };
  62744. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62745. var image = pixel_data, colormap = palettes;
  62746. var width = header.width, height = header.height;
  62747. var color, i = 0, x, y;
  62748. var imageData = new Uint8Array(width * height * 4);
  62749. for (y = y_start; y !== y_end; y += y_step) {
  62750. for (x = x_start; x !== x_end; x += x_step, i++) {
  62751. color = image[i];
  62752. imageData[(x + width * y) * 4 + 3] = 255;
  62753. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  62754. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  62755. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  62756. }
  62757. }
  62758. return imageData;
  62759. };
  62760. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62761. var image = pixel_data;
  62762. var width = header.width, height = header.height;
  62763. var color, i = 0, x, y;
  62764. var imageData = new Uint8Array(width * height * 4);
  62765. for (y = y_start; y !== y_end; y += y_step) {
  62766. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62767. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  62768. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  62769. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  62770. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  62771. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  62772. }
  62773. }
  62774. return imageData;
  62775. };
  62776. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62777. var image = pixel_data;
  62778. var width = header.width, height = header.height;
  62779. var i = 0, x, y;
  62780. var imageData = new Uint8Array(width * height * 4);
  62781. for (y = y_start; y !== y_end; y += y_step) {
  62782. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  62783. imageData[(x + width * y) * 4 + 3] = 255;
  62784. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62785. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  62786. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  62787. }
  62788. }
  62789. return imageData;
  62790. };
  62791. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62792. var image = pixel_data;
  62793. var width = header.width, height = header.height;
  62794. var i = 0, x, y;
  62795. var imageData = new Uint8Array(width * height * 4);
  62796. for (y = y_start; y !== y_end; y += y_step) {
  62797. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  62798. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62799. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  62800. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  62801. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  62802. }
  62803. }
  62804. return imageData;
  62805. };
  62806. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62807. var image = pixel_data;
  62808. var width = header.width, height = header.height;
  62809. var color, i = 0, x, y;
  62810. var imageData = new Uint8Array(width * height * 4);
  62811. for (y = y_start; y !== y_end; y += y_step) {
  62812. for (x = x_start; x !== x_end; x += x_step, i++) {
  62813. color = image[i];
  62814. imageData[(x + width * y) * 4 + 0] = color;
  62815. imageData[(x + width * y) * 4 + 1] = color;
  62816. imageData[(x + width * y) * 4 + 2] = color;
  62817. imageData[(x + width * y) * 4 + 3] = 255;
  62818. }
  62819. }
  62820. return imageData;
  62821. };
  62822. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62823. var image = pixel_data;
  62824. var width = header.width, height = header.height;
  62825. var i = 0, x, y;
  62826. var imageData = new Uint8Array(width * height * 4);
  62827. for (y = y_start; y !== y_end; y += y_step) {
  62828. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62829. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  62830. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  62831. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62832. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  62833. }
  62834. }
  62835. return imageData;
  62836. };
  62837. TGATools._TYPE_NO_DATA = 0;
  62838. TGATools._TYPE_INDEXED = 1;
  62839. TGATools._TYPE_RGB = 2;
  62840. TGATools._TYPE_GREY = 3;
  62841. TGATools._TYPE_RLE_INDEXED = 9;
  62842. TGATools._TYPE_RLE_RGB = 10;
  62843. TGATools._TYPE_RLE_GREY = 11;
  62844. TGATools._ORIGIN_MASK = 0x30;
  62845. TGATools._ORIGIN_SHIFT = 0x04;
  62846. TGATools._ORIGIN_BL = 0x00;
  62847. TGATools._ORIGIN_BR = 0x01;
  62848. TGATools._ORIGIN_UL = 0x02;
  62849. TGATools._ORIGIN_UR = 0x03;
  62850. return TGATools;
  62851. }());
  62852. Internals.TGATools = TGATools;
  62853. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62854. })(BABYLON || (BABYLON = {}));
  62855. //# sourceMappingURL=babylon.tga.js.map
  62856. var BABYLON;
  62857. (function (BABYLON) {
  62858. var Internals;
  62859. (function (Internals) {
  62860. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  62861. // All values and structures referenced from:
  62862. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  62863. var DDS_MAGIC = 0x20534444;
  62864. 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;
  62865. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  62866. 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;
  62867. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  62868. function FourCCToInt32(value) {
  62869. return value.charCodeAt(0) +
  62870. (value.charCodeAt(1) << 8) +
  62871. (value.charCodeAt(2) << 16) +
  62872. (value.charCodeAt(3) << 24);
  62873. }
  62874. function Int32ToFourCC(value) {
  62875. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  62876. }
  62877. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  62878. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  62879. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  62880. var FOURCC_DX10 = FourCCToInt32("DX10");
  62881. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  62882. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  62883. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  62884. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  62885. var headerLengthInt = 31; // The header length in 32 bit ints
  62886. // Offsets into the header array
  62887. var off_magic = 0;
  62888. var off_size = 1;
  62889. var off_flags = 2;
  62890. var off_height = 3;
  62891. var off_width = 4;
  62892. var off_mipmapCount = 7;
  62893. var off_pfFlags = 20;
  62894. var off_pfFourCC = 21;
  62895. var off_RGBbpp = 22;
  62896. var off_RMask = 23;
  62897. var off_GMask = 24;
  62898. var off_BMask = 25;
  62899. var off_AMask = 26;
  62900. var off_caps1 = 27;
  62901. var off_caps2 = 28;
  62902. var off_caps3 = 29;
  62903. var off_caps4 = 30;
  62904. var off_dxgiFormat = 32;
  62905. ;
  62906. var DDSTools = (function () {
  62907. function DDSTools() {
  62908. }
  62909. DDSTools.GetDDSInfo = function (arrayBuffer) {
  62910. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  62911. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  62912. var mipmapCount = 1;
  62913. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  62914. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62915. }
  62916. var fourCC = header[off_pfFourCC];
  62917. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  62918. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62919. switch (fourCC) {
  62920. case FOURCC_D3DFMT_R16G16B16A16F:
  62921. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62922. break;
  62923. case FOURCC_D3DFMT_R32G32B32A32F:
  62924. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62925. break;
  62926. case FOURCC_DX10:
  62927. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  62928. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62929. break;
  62930. }
  62931. }
  62932. return {
  62933. width: header[off_width],
  62934. height: header[off_height],
  62935. mipmapCount: mipmapCount,
  62936. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  62937. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  62938. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  62939. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  62940. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  62941. dxgiFormat: dxgiFormat,
  62942. textureType: textureType
  62943. };
  62944. };
  62945. DDSTools._ToHalfFloat = function (value) {
  62946. if (!DDSTools._FloatView) {
  62947. DDSTools._FloatView = new Float32Array(1);
  62948. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  62949. }
  62950. DDSTools._FloatView[0] = value;
  62951. var x = DDSTools._Int32View[0];
  62952. var bits = (x >> 16) & 0x8000; /* Get the sign */
  62953. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  62954. var e = (x >> 23) & 0xff; /* Using int is faster here */
  62955. /* If zero, or denormal, or exponent underflows too much for a denormal
  62956. * half, return signed zero. */
  62957. if (e < 103) {
  62958. return bits;
  62959. }
  62960. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  62961. if (e > 142) {
  62962. bits |= 0x7c00;
  62963. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  62964. * not Inf, so make sure we set one mantissa bit too. */
  62965. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  62966. return bits;
  62967. }
  62968. /* If exponent underflows but not too much, return a denormal */
  62969. if (e < 113) {
  62970. m |= 0x0800;
  62971. /* Extra rounding may overflow and set mantissa to 0 and exponent
  62972. * to 1, which is OK. */
  62973. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  62974. return bits;
  62975. }
  62976. bits |= ((e - 112) << 10) | (m >> 1);
  62977. bits += m & 1;
  62978. return bits;
  62979. };
  62980. DDSTools._FromHalfFloat = function (value) {
  62981. var s = (value & 0x8000) >> 15;
  62982. var e = (value & 0x7C00) >> 10;
  62983. var f = value & 0x03FF;
  62984. if (e === 0) {
  62985. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  62986. }
  62987. else if (e == 0x1F) {
  62988. return f ? NaN : ((s ? -1 : 1) * Infinity);
  62989. }
  62990. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  62991. };
  62992. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62993. var destArray = new Float32Array(dataLength);
  62994. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62995. var index = 0;
  62996. for (var y = 0; y < height; y++) {
  62997. for (var x = 0; x < width; x++) {
  62998. var srcPos = (x + y * width) * 4;
  62999. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  63000. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  63001. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  63002. if (DDSTools.StoreLODInAlphaChannel) {
  63003. destArray[index + 3] = lod;
  63004. }
  63005. else {
  63006. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  63007. }
  63008. index += 4;
  63009. }
  63010. }
  63011. return destArray;
  63012. };
  63013. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63014. if (DDSTools.StoreLODInAlphaChannel) {
  63015. var destArray = new Uint16Array(dataLength);
  63016. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63017. var index = 0;
  63018. for (var y = 0; y < height; y++) {
  63019. for (var x = 0; x < width; x++) {
  63020. var srcPos = (x + y * width) * 4;
  63021. destArray[index] = srcData[srcPos];
  63022. destArray[index + 1] = srcData[srcPos + 1];
  63023. destArray[index + 2] = srcData[srcPos + 2];
  63024. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  63025. index += 4;
  63026. }
  63027. }
  63028. return destArray;
  63029. }
  63030. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  63031. };
  63032. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63033. if (DDSTools.StoreLODInAlphaChannel) {
  63034. var destArray = new Float32Array(dataLength);
  63035. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63036. var index = 0;
  63037. for (var y = 0; y < height; y++) {
  63038. for (var x = 0; x < width; x++) {
  63039. var srcPos = (x + y * width) * 4;
  63040. destArray[index] = srcData[srcPos];
  63041. destArray[index + 1] = srcData[srcPos + 1];
  63042. destArray[index + 2] = srcData[srcPos + 2];
  63043. destArray[index + 3] = lod;
  63044. index += 4;
  63045. }
  63046. }
  63047. return destArray;
  63048. }
  63049. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  63050. };
  63051. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63052. var destArray = new Uint8Array(dataLength);
  63053. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63054. var index = 0;
  63055. for (var y = 0; y < height; y++) {
  63056. for (var x = 0; x < width; x++) {
  63057. var srcPos = (x + y * width) * 4;
  63058. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  63059. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  63060. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  63061. if (DDSTools.StoreLODInAlphaChannel) {
  63062. destArray[index + 3] = lod;
  63063. }
  63064. else {
  63065. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  63066. }
  63067. index += 4;
  63068. }
  63069. }
  63070. return destArray;
  63071. };
  63072. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63073. var destArray = new Uint8Array(dataLength);
  63074. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63075. var index = 0;
  63076. for (var y = 0; y < height; y++) {
  63077. for (var x = 0; x < width; x++) {
  63078. var srcPos = (x + y * width) * 4;
  63079. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  63080. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  63081. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  63082. if (DDSTools.StoreLODInAlphaChannel) {
  63083. destArray[index + 3] = lod;
  63084. }
  63085. else {
  63086. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  63087. }
  63088. index += 4;
  63089. }
  63090. }
  63091. return destArray;
  63092. };
  63093. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63094. var byteArray = new Uint8Array(dataLength);
  63095. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63096. var index = 0;
  63097. for (var y = 0; y < height; y++) {
  63098. for (var x = 0; x < width; x++) {
  63099. var srcPos = (x + y * width) * 4;
  63100. byteArray[index] = srcData[srcPos + 2];
  63101. byteArray[index + 1] = srcData[srcPos + 1];
  63102. byteArray[index + 2] = srcData[srcPos];
  63103. byteArray[index + 3] = srcData[srcPos + 3];
  63104. index += 4;
  63105. }
  63106. }
  63107. return byteArray;
  63108. };
  63109. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63110. var byteArray = new Uint8Array(dataLength);
  63111. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63112. var index = 0;
  63113. for (var y = 0; y < height; y++) {
  63114. for (var x = 0; x < width; x++) {
  63115. var srcPos = (x + y * width) * 3;
  63116. byteArray[index] = srcData[srcPos + 2];
  63117. byteArray[index + 1] = srcData[srcPos + 1];
  63118. byteArray[index + 2] = srcData[srcPos];
  63119. index += 3;
  63120. }
  63121. }
  63122. return byteArray;
  63123. };
  63124. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63125. var byteArray = new Uint8Array(dataLength);
  63126. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63127. var index = 0;
  63128. for (var y = 0; y < height; y++) {
  63129. for (var x = 0; x < width; x++) {
  63130. var srcPos = (x + y * width);
  63131. byteArray[index] = srcData[srcPos];
  63132. index++;
  63133. }
  63134. }
  63135. return byteArray;
  63136. };
  63137. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  63138. if (lodIndex === void 0) { lodIndex = -1; }
  63139. var ext = engine.getCaps().s3tc;
  63140. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  63141. if (header[off_magic] != DDS_MAGIC) {
  63142. BABYLON.Tools.Error("Invalid magic number in DDS header");
  63143. return;
  63144. }
  63145. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  63146. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  63147. return;
  63148. }
  63149. if (info.isCompressed && !ext) {
  63150. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  63151. return;
  63152. }
  63153. var bpp = header[off_RGBbpp];
  63154. dataOffset = header[off_size] + 4;
  63155. var computeFormats = false;
  63156. if (info.isFourCC) {
  63157. fourCC = header[off_pfFourCC];
  63158. switch (fourCC) {
  63159. case FOURCC_DXT1:
  63160. blockBytes = 8;
  63161. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  63162. break;
  63163. case FOURCC_DXT3:
  63164. blockBytes = 16;
  63165. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  63166. break;
  63167. case FOURCC_DXT5:
  63168. blockBytes = 16;
  63169. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  63170. break;
  63171. case FOURCC_D3DFMT_R16G16B16A16F:
  63172. computeFormats = true;
  63173. break;
  63174. case FOURCC_D3DFMT_R32G32B32A32F:
  63175. computeFormats = true;
  63176. break;
  63177. case FOURCC_DX10:
  63178. // There is an additionnal header so dataOffset need to be changed
  63179. dataOffset += 5 * 4; // 5 uints
  63180. var supported = false;
  63181. switch (info.dxgiFormat) {
  63182. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  63183. computeFormats = true;
  63184. supported = true;
  63185. break;
  63186. case DXGI_FORMAT_B8G8R8X8_UNORM:
  63187. info.isRGB = true;
  63188. info.isFourCC = false;
  63189. bpp = 32;
  63190. supported = true;
  63191. break;
  63192. }
  63193. if (supported) {
  63194. break;
  63195. }
  63196. default:
  63197. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  63198. return;
  63199. }
  63200. }
  63201. if (computeFormats) {
  63202. format = engine._getWebGLTextureType(info.textureType);
  63203. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63204. }
  63205. mipmapCount = 1;
  63206. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  63207. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63208. }
  63209. for (var face = 0; face < faces; face++) {
  63210. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63211. width = header[off_width];
  63212. height = header[off_height];
  63213. for (mip = 0; mip < mipmapCount; ++mip) {
  63214. if (lodIndex === -1 || lodIndex === mip) {
  63215. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  63216. var i = (lodIndex === -1) ? mip : 0;
  63217. if (!info.isCompressed && info.isFourCC) {
  63218. dataLength = width * height * 4;
  63219. var floatArray;
  63220. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  63221. if (bpp === 128) {
  63222. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63223. }
  63224. else if (bpp === 64) {
  63225. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63226. }
  63227. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63228. format = engine._getWebGLTextureType(info.textureType);
  63229. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63230. }
  63231. else {
  63232. if (bpp === 128) {
  63233. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63234. }
  63235. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  63236. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63237. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63238. format = engine._getWebGLTextureType(info.textureType);
  63239. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63240. }
  63241. else {
  63242. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63243. }
  63244. }
  63245. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  63246. }
  63247. else if (info.isRGB) {
  63248. if (bpp === 24) {
  63249. dataLength = width * height * 3;
  63250. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63251. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  63252. }
  63253. else {
  63254. dataLength = width * height * 4;
  63255. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63256. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  63257. }
  63258. }
  63259. else if (info.isLuminance) {
  63260. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  63261. var unpaddedRowSize = width;
  63262. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  63263. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  63264. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63265. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  63266. }
  63267. else {
  63268. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  63269. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  63270. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  63271. }
  63272. }
  63273. dataOffset += width * height * (bpp / 8);
  63274. width *= 0.5;
  63275. height *= 0.5;
  63276. width = Math.max(1.0, width);
  63277. height = Math.max(1.0, height);
  63278. }
  63279. }
  63280. };
  63281. DDSTools.StoreLODInAlphaChannel = false;
  63282. return DDSTools;
  63283. }());
  63284. Internals.DDSTools = DDSTools;
  63285. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63286. })(BABYLON || (BABYLON = {}));
  63287. //# sourceMappingURL=babylon.dds.js.map
  63288. var BABYLON;
  63289. (function (BABYLON) {
  63290. var Internals;
  63291. (function (Internals) {
  63292. /**
  63293. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  63294. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  63295. */
  63296. var KhronosTextureContainer = (function () {
  63297. /**
  63298. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  63299. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  63300. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  63301. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  63302. */
  63303. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  63304. this.arrayBuffer = arrayBuffer;
  63305. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  63306. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  63307. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  63308. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  63309. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  63310. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  63311. BABYLON.Tools.Error("texture missing KTX identifier");
  63312. return;
  63313. }
  63314. // load the reset of the header in native 32 bit int
  63315. var header = new Int32Array(this.arrayBuffer, 12, 13);
  63316. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  63317. var oppositeEndianess = header[0] === 0x01020304;
  63318. // read all the header elements in order they exist in the file, without modification (sans endainness)
  63319. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  63320. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  63321. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  63322. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  63323. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  63324. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  63325. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  63326. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  63327. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  63328. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  63329. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  63330. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  63331. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  63332. if (this.glType !== 0) {
  63333. BABYLON.Tools.Error("only compressed formats currently supported");
  63334. return;
  63335. }
  63336. else {
  63337. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  63338. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  63339. }
  63340. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  63341. BABYLON.Tools.Error("only 2D textures currently supported");
  63342. return;
  63343. }
  63344. if (this.numberOfArrayElements !== 0) {
  63345. BABYLON.Tools.Error("texture arrays not currently supported");
  63346. return;
  63347. }
  63348. if (this.numberOfFaces !== facesExpected) {
  63349. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  63350. return;
  63351. }
  63352. // we now have a completely validated file, so could use existence of loadType as success
  63353. // would need to make this more elaborate & adjust checks above to support more than one load type
  63354. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  63355. }
  63356. // not as fast hardware based, but will probably never need to use
  63357. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  63358. return ((val & 0xFF) << 24)
  63359. | ((val & 0xFF00) << 8)
  63360. | ((val >> 8) & 0xFF00)
  63361. | ((val >> 24) & 0xFF);
  63362. };
  63363. /**
  63364. * It is assumed that the texture has already been created & is currently bound
  63365. */
  63366. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  63367. switch (this.loadType) {
  63368. case KhronosTextureContainer.COMPRESSED_2D:
  63369. this._upload2DCompressedLevels(gl, loadMipmaps);
  63370. break;
  63371. case KhronosTextureContainer.TEX_2D:
  63372. case KhronosTextureContainer.COMPRESSED_3D:
  63373. case KhronosTextureContainer.TEX_3D:
  63374. }
  63375. };
  63376. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  63377. // initialize width & height for level 1
  63378. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  63379. var width = this.pixelWidth;
  63380. var height = this.pixelHeight;
  63381. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  63382. for (var level = 0; level < mipmapCount; level++) {
  63383. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  63384. for (var face = 0; face < this.numberOfFaces; face++) {
  63385. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63386. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  63387. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  63388. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  63389. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  63390. }
  63391. width = Math.max(1.0, width * 0.5);
  63392. height = Math.max(1.0, height * 0.5);
  63393. }
  63394. };
  63395. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  63396. // load types
  63397. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  63398. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  63399. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  63400. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  63401. return KhronosTextureContainer;
  63402. }());
  63403. Internals.KhronosTextureContainer = KhronosTextureContainer;
  63404. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63405. })(BABYLON || (BABYLON = {}));
  63406. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  63407. var BABYLON;
  63408. (function (BABYLON) {
  63409. var DynamicFloatArrayElementInfo = (function () {
  63410. function DynamicFloatArrayElementInfo() {
  63411. }
  63412. return DynamicFloatArrayElementInfo;
  63413. }());
  63414. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  63415. /**
  63416. * 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.
  63417. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  63418. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  63419. * 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.
  63420. * 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.
  63421. * 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".
  63422. */
  63423. var DynamicFloatArray = (function () {
  63424. /**
  63425. * Construct an instance of the dynamic float array
  63426. * @param stride size of one element in float (i.e. not bytes!)
  63427. * @param initialElementCount the number of available entries at construction
  63428. */
  63429. function DynamicFloatArray(stride, initialElementCount) {
  63430. this.compareValueOffset = null;
  63431. this.sortingAscending = true;
  63432. this._stride = stride;
  63433. this.buffer = new Float32Array(stride * initialElementCount);
  63434. this._lastUsed = 0;
  63435. this._firstFree = 0;
  63436. this._allEntries = new Array(initialElementCount);
  63437. this._freeEntries = new Array(initialElementCount);
  63438. for (var i = 0; i < initialElementCount; i++) {
  63439. var element = new DynamicFloatArrayElementInfo();
  63440. element.offset = i * stride;
  63441. this._allEntries[i] = element;
  63442. this._freeEntries[initialElementCount - i - 1] = element;
  63443. }
  63444. }
  63445. /**
  63446. * Allocate an element in the array.
  63447. * @return the element info instance that contains the offset into the main buffer of the element's location.
  63448. * Beware, this offset may change when you call pack()
  63449. */
  63450. DynamicFloatArray.prototype.allocElement = function () {
  63451. if (this._freeEntries.length === 0) {
  63452. this._growBuffer();
  63453. }
  63454. var el = this._freeEntries.pop();
  63455. this._lastUsed = Math.max(el.offset, this._lastUsed);
  63456. if (el.offset === this._firstFree) {
  63457. if (this._freeEntries.length > 0) {
  63458. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  63459. }
  63460. else {
  63461. this._firstFree += this._stride;
  63462. }
  63463. }
  63464. return el;
  63465. };
  63466. /**
  63467. * Free the element corresponding to the given element info
  63468. * @param elInfo the element that describe the allocated element
  63469. */
  63470. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  63471. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  63472. this._freeEntries.push(elInfo);
  63473. };
  63474. /**
  63475. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  63476. * 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().
  63477. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  63478. */
  63479. DynamicFloatArray.prototype.pack = function () {
  63480. // no free slot? no need to pack
  63481. if (this._freeEntries.length === 0) {
  63482. return this.buffer;
  63483. }
  63484. // If the buffer is already packed the last used will always be lower than the first free
  63485. // 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.
  63486. if (this._lastUsed < this._firstFree) {
  63487. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  63488. return elementsBuffer_1;
  63489. }
  63490. var s = this._stride;
  63491. // 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
  63492. var lastFree = new DynamicFloatArrayElementInfo();
  63493. lastFree.offset = this.totalElementCount * s;
  63494. this._freeEntries.push(lastFree);
  63495. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  63496. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63497. var firstFreeSlotOffset = sortedFree[0].offset;
  63498. var freeZoneSize = 1;
  63499. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  63500. var prevOffset = sortedFree[0].offset;
  63501. for (var i = 1; i < sortedFree.length; i++) {
  63502. // 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
  63503. if (firstFreeSlotOffset >= occupiedZoneSize) {
  63504. break;
  63505. }
  63506. var curFree = sortedFree[i];
  63507. var curOffset = curFree.offset;
  63508. // Compute the distance between this offset and the previous
  63509. var distance = curOffset - prevOffset;
  63510. // If the distance is the stride size, they are adjacent, it good, move to the next
  63511. if (distance === s) {
  63512. // Free zone is one element bigger
  63513. ++freeZoneSize;
  63514. // as we're about to iterate to the next, the cur becomes the previous...
  63515. prevOffset = curOffset;
  63516. continue;
  63517. }
  63518. // Distance is bigger, which means there's x element between the previous free and this one
  63519. var usedRange = (distance / s) - 1;
  63520. // Two cases the free zone is smaller than the data to move or bigger
  63521. // Copy what can fit in the free zone
  63522. var curMoveOffset = curOffset - s;
  63523. var copyCount = Math.min(freeZoneSize, usedRange);
  63524. for (var j = 0; j < copyCount; j++) {
  63525. var freeI = firstFreeSlotOffset / s;
  63526. var curI = curMoveOffset / s;
  63527. var moveEl = sortedAll[curI];
  63528. this._moveElement(moveEl, firstFreeSlotOffset);
  63529. var replacedEl = sortedAll[freeI];
  63530. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  63531. replacedEl.offset = curMoveOffset;
  63532. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  63533. sortedAll[freeI] = moveEl;
  63534. sortedAll[curI] = replacedEl;
  63535. curMoveOffset -= s;
  63536. firstFreeSlotOffset += s;
  63537. }
  63538. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  63539. if (freeZoneSize <= usedRange) {
  63540. firstFreeSlotOffset = curMoveOffset + s;
  63541. freeZoneSize = 1 + copyCount;
  63542. }
  63543. else {
  63544. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  63545. }
  63546. // as we're about to iterate to the next, the cur becomes the previous...
  63547. prevOffset = curOffset;
  63548. }
  63549. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  63550. this._lastUsed = firstFreeSlotOffset - s;
  63551. this._firstFree = firstFreeSlotOffset;
  63552. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  63553. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  63554. this._allEntries = sortedAll;
  63555. return elementsBuffer;
  63556. };
  63557. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  63558. for (var i = 0; i < this._stride; i++) {
  63559. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  63560. }
  63561. element.offset = destOffset;
  63562. };
  63563. DynamicFloatArray.prototype._growBuffer = function () {
  63564. // Allocate the new buffer with 50% more entries, copy the content of the current one
  63565. var newElCount = Math.floor(this.totalElementCount * 1.5);
  63566. var newBuffer = new Float32Array(newElCount * this._stride);
  63567. newBuffer.set(this.buffer);
  63568. var curCount = this.totalElementCount;
  63569. var addedCount = newElCount - this.totalElementCount;
  63570. for (var i = 0; i < addedCount; i++) {
  63571. var element = new DynamicFloatArrayElementInfo();
  63572. element.offset = (curCount + i) * this.stride;
  63573. this._allEntries.push(element);
  63574. this._freeEntries[addedCount - i - 1] = element;
  63575. }
  63576. this._firstFree = curCount * this.stride;
  63577. this.buffer = newBuffer;
  63578. };
  63579. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  63580. /**
  63581. * Get the total count of entries that can fit in the current buffer
  63582. * @returns the elements count
  63583. */
  63584. get: function () {
  63585. return this._allEntries.length;
  63586. },
  63587. enumerable: true,
  63588. configurable: true
  63589. });
  63590. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  63591. /**
  63592. * Get the count of free entries that can still be allocated without resizing the buffer
  63593. * @returns the free elements count
  63594. */
  63595. get: function () {
  63596. return this._freeEntries.length;
  63597. },
  63598. enumerable: true,
  63599. configurable: true
  63600. });
  63601. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  63602. /**
  63603. * Get the count of allocated elements
  63604. * @returns the allocated elements count
  63605. */
  63606. get: function () {
  63607. return this._allEntries.length - this._freeEntries.length;
  63608. },
  63609. enumerable: true,
  63610. configurable: true
  63611. });
  63612. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  63613. /**
  63614. * Return the size of one element in float
  63615. * @returns the size in float
  63616. */
  63617. get: function () {
  63618. return this._stride;
  63619. },
  63620. enumerable: true,
  63621. configurable: true
  63622. });
  63623. DynamicFloatArray.prototype.sort = function () {
  63624. var _this = this;
  63625. if (!this.compareValueOffset) {
  63626. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  63627. }
  63628. var count = this.usedElementCount;
  63629. // Do we have to (re)create the sort table?
  63630. if (!this._sortTable || this._sortTable.length < count) {
  63631. // 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...
  63632. var newCount = Math.min(this.totalElementCount, count * 2);
  63633. this._sortTable = new Array(newCount);
  63634. }
  63635. if (!this._sortedTable || this._sortedTable.length !== count) {
  63636. this._sortedTable = new Array(count);
  63637. }
  63638. // Because, you know...
  63639. this.pack();
  63640. //let stride = this.stride;
  63641. //for (let i = 0; i < count; i++) {
  63642. // let si = this._sortTable[i];
  63643. // if (!si) {
  63644. // si = new SortInfo();
  63645. // this._sortTable[i] = si;
  63646. // }
  63647. // si.entry = this._allEntries[i];
  63648. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  63649. // si.swapedOffset = null;
  63650. // this._sortedTable[i] = si;
  63651. //}
  63652. var curOffset = 0;
  63653. var stride = this.stride;
  63654. for (var i = 0; i < count; i++, curOffset += stride) {
  63655. var si = this._sortTable[i];
  63656. if (!si) {
  63657. si = new SortInfo();
  63658. this._sortTable[i] = si;
  63659. }
  63660. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  63661. si.offset = curOffset;
  63662. si.swapedOffset = null;
  63663. this._sortedTable[i] = si;
  63664. }
  63665. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  63666. if (this.sortingAscending) {
  63667. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  63668. }
  63669. else {
  63670. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  63671. }
  63672. var swapElements = function (src, dst) {
  63673. for (var i = 0; i < stride; i++) {
  63674. var tps = _this.buffer[dst + i];
  63675. _this.buffer[dst + i] = _this.buffer[src + i];
  63676. _this.buffer[src + i] = tps;
  63677. }
  63678. };
  63679. // 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:
  63680. // 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),
  63681. // and I still want something with a good algorithm complexity.
  63682. // 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,
  63683. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  63684. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  63685. // 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
  63686. // until we find a SortInfo object without a swapedOffset which means we got the right location
  63687. // 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
  63688. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  63689. for (var i = 0; i < count; i++) {
  63690. // Get the element to move
  63691. var sourceSI = this._sortedTable[i];
  63692. var destSI = this._sortTable[i];
  63693. var sourceOff = sourceSI.offset;
  63694. // If the source changed location, find the new one
  63695. if (sourceSI.swapedOffset) {
  63696. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  63697. var curSI = sourceSI;
  63698. while (curSI.swapedOffset) {
  63699. curSI = this._sortTable[curSI.swapedOffset / stride];
  63700. }
  63701. // Finally get the right location
  63702. sourceOff = curSI.offset;
  63703. }
  63704. // Tag the element being replaced with its new location
  63705. destSI.swapedOffset = sourceOff;
  63706. // Swap elements (only if needed)
  63707. if (sourceOff !== destSI.offset) {
  63708. swapElements(sourceOff, destSI.offset);
  63709. }
  63710. // Update the offset in the corresponding DFAE
  63711. //sourceSI.entry.offset = destSI.entry.offset;
  63712. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  63713. }
  63714. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63715. return true;
  63716. };
  63717. return DynamicFloatArray;
  63718. }());
  63719. BABYLON.DynamicFloatArray = DynamicFloatArray;
  63720. var SortInfo = (function () {
  63721. function SortInfo() {
  63722. this.compareData = this.offset = this.swapedOffset = null;
  63723. }
  63724. return SortInfo;
  63725. }());
  63726. })(BABYLON || (BABYLON = {}));
  63727. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  63728. var BABYLON;
  63729. (function (BABYLON) {
  63730. var Debug;
  63731. (function (Debug) {
  63732. /**
  63733. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  63734. */
  63735. var SkeletonViewer = (function () {
  63736. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  63737. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63738. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63739. this.skeleton = skeleton;
  63740. this.mesh = mesh;
  63741. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63742. this.renderingGroupId = renderingGroupId;
  63743. this.color = BABYLON.Color3.White();
  63744. this._debugLines = [];
  63745. this._isEnabled = false;
  63746. this._scene = scene;
  63747. this.update();
  63748. this._renderFunction = this.update.bind(this);
  63749. }
  63750. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63751. get: function () {
  63752. return this._isEnabled;
  63753. },
  63754. set: function (value) {
  63755. if (this._isEnabled === value) {
  63756. return;
  63757. }
  63758. this._isEnabled = value;
  63759. if (value) {
  63760. this._scene.registerBeforeRender(this._renderFunction);
  63761. }
  63762. else {
  63763. this._scene.unregisterBeforeRender(this._renderFunction);
  63764. }
  63765. },
  63766. enumerable: true,
  63767. configurable: true
  63768. });
  63769. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63770. if (x === void 0) { x = 0; }
  63771. if (y === void 0) { y = 0; }
  63772. if (z === void 0) { z = 0; }
  63773. var tmat = BABYLON.Tmp.Matrix[0];
  63774. var parentBone = bone.getParent();
  63775. tmat.copyFrom(bone.getLocalMatrix());
  63776. if (x !== 0 || y !== 0 || z !== 0) {
  63777. var tmat2 = BABYLON.Tmp.Matrix[1];
  63778. BABYLON.Matrix.IdentityToRef(tmat2);
  63779. tmat2.m[12] = x;
  63780. tmat2.m[13] = y;
  63781. tmat2.m[14] = z;
  63782. tmat2.multiplyToRef(tmat, tmat);
  63783. }
  63784. if (parentBone) {
  63785. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63786. }
  63787. tmat.multiplyToRef(meshMat, tmat);
  63788. position.x = tmat.m[12];
  63789. position.y = tmat.m[13];
  63790. position.z = tmat.m[14];
  63791. };
  63792. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63793. var len = bones.length;
  63794. var meshPos = this.mesh.position;
  63795. for (var i = 0; i < len; i++) {
  63796. var bone = bones[i];
  63797. var points = this._debugLines[i];
  63798. if (!points) {
  63799. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63800. this._debugLines[i] = points;
  63801. }
  63802. this._getBonePosition(points[0], bone, meshMat);
  63803. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63804. points[0].subtractInPlace(meshPos);
  63805. points[1].subtractInPlace(meshPos);
  63806. }
  63807. };
  63808. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63809. var len = bones.length;
  63810. var boneNum = 0;
  63811. var meshPos = this.mesh.position;
  63812. for (var i = len - 1; i >= 0; i--) {
  63813. var childBone = bones[i];
  63814. var parentBone = childBone.getParent();
  63815. if (!parentBone) {
  63816. continue;
  63817. }
  63818. var points = this._debugLines[boneNum];
  63819. if (!points) {
  63820. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63821. this._debugLines[boneNum] = points;
  63822. }
  63823. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63824. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63825. points[0].subtractInPlace(meshPos);
  63826. points[1].subtractInPlace(meshPos);
  63827. boneNum++;
  63828. }
  63829. };
  63830. SkeletonViewer.prototype.update = function () {
  63831. if (this.autoUpdateBonesMatrices) {
  63832. this.skeleton.computeAbsoluteTransforms();
  63833. }
  63834. if (this.skeleton.bones[0].length === undefined) {
  63835. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63836. }
  63837. else {
  63838. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63839. }
  63840. if (!this._debugMesh) {
  63841. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  63842. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63843. }
  63844. else {
  63845. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63846. }
  63847. this._debugMesh.position.copyFrom(this.mesh.position);
  63848. this._debugMesh.color = this.color;
  63849. };
  63850. SkeletonViewer.prototype.dispose = function () {
  63851. if (this._debugMesh) {
  63852. this.isEnabled = false;
  63853. this._debugMesh.dispose();
  63854. this._debugMesh = null;
  63855. }
  63856. };
  63857. return SkeletonViewer;
  63858. }());
  63859. Debug.SkeletonViewer = SkeletonViewer;
  63860. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63861. })(BABYLON || (BABYLON = {}));
  63862. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63863. var BABYLON;
  63864. (function (BABYLON) {
  63865. var Debug;
  63866. (function (Debug) {
  63867. var AxesViewer = (function () {
  63868. function AxesViewer(scene, scaleLines) {
  63869. if (scaleLines === void 0) { scaleLines = 1; }
  63870. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63871. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63872. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63873. this.scaleLines = 1;
  63874. this.scaleLines = scaleLines;
  63875. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63876. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63877. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63878. this._xmesh.renderingGroupId = 2;
  63879. this._ymesh.renderingGroupId = 2;
  63880. this._zmesh.renderingGroupId = 2;
  63881. this._xmesh.material.checkReadyOnlyOnce = true;
  63882. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63883. this._ymesh.material.checkReadyOnlyOnce = true;
  63884. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63885. this._zmesh.material.checkReadyOnlyOnce = true;
  63886. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63887. this.scene = scene;
  63888. }
  63889. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63890. var scaleLines = this.scaleLines;
  63891. this._xmesh.position.copyFrom(position);
  63892. this._ymesh.position.copyFrom(position);
  63893. this._zmesh.position.copyFrom(position);
  63894. var point2 = this._xline[1];
  63895. point2.x = xaxis.x * scaleLines;
  63896. point2.y = xaxis.y * scaleLines;
  63897. point2.z = xaxis.z * scaleLines;
  63898. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  63899. point2 = this._yline[1];
  63900. point2.x = yaxis.x * scaleLines;
  63901. point2.y = yaxis.y * scaleLines;
  63902. point2.z = yaxis.z * scaleLines;
  63903. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  63904. point2 = this._zline[1];
  63905. point2.x = zaxis.x * scaleLines;
  63906. point2.y = zaxis.y * scaleLines;
  63907. point2.z = zaxis.z * scaleLines;
  63908. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  63909. };
  63910. AxesViewer.prototype.dispose = function () {
  63911. if (this._xmesh) {
  63912. this._xmesh.dispose();
  63913. this._ymesh.dispose();
  63914. this._zmesh.dispose();
  63915. this._xmesh = null;
  63916. this._ymesh = null;
  63917. this._zmesh = null;
  63918. this._xline = null;
  63919. this._yline = null;
  63920. this._zline = null;
  63921. this.scene = null;
  63922. }
  63923. };
  63924. return AxesViewer;
  63925. }());
  63926. Debug.AxesViewer = AxesViewer;
  63927. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63928. })(BABYLON || (BABYLON = {}));
  63929. //# sourceMappingURL=babylon.axesViewer.js.map
  63930. var BABYLON;
  63931. (function (BABYLON) {
  63932. var Debug;
  63933. (function (Debug) {
  63934. var BoneAxesViewer = (function (_super) {
  63935. __extends(BoneAxesViewer, _super);
  63936. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63937. if (scaleLines === void 0) { scaleLines = 1; }
  63938. var _this = _super.call(this, scene, scaleLines) || this;
  63939. _this.pos = BABYLON.Vector3.Zero();
  63940. _this.xaxis = BABYLON.Vector3.Zero();
  63941. _this.yaxis = BABYLON.Vector3.Zero();
  63942. _this.zaxis = BABYLON.Vector3.Zero();
  63943. _this.mesh = mesh;
  63944. _this.bone = bone;
  63945. return _this;
  63946. }
  63947. BoneAxesViewer.prototype.update = function () {
  63948. var bone = this.bone;
  63949. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63950. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63951. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63952. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63953. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63954. };
  63955. BoneAxesViewer.prototype.dispose = function () {
  63956. if (this.pos) {
  63957. this.pos = null;
  63958. this.xaxis = null;
  63959. this.yaxis = null;
  63960. this.zaxis = null;
  63961. this.mesh = null;
  63962. this.bone = null;
  63963. _super.prototype.dispose.call(this);
  63964. }
  63965. };
  63966. return BoneAxesViewer;
  63967. }(Debug.AxesViewer));
  63968. Debug.BoneAxesViewer = BoneAxesViewer;
  63969. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63970. })(BABYLON || (BABYLON = {}));
  63971. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63972. var BABYLON;
  63973. (function (BABYLON) {
  63974. var RayHelper = (function () {
  63975. function RayHelper(ray) {
  63976. this.ray = ray;
  63977. }
  63978. RayHelper.CreateAndShow = function (ray, scene, color) {
  63979. var helper = new RayHelper(ray);
  63980. helper.show(scene, color);
  63981. return helper;
  63982. };
  63983. RayHelper.prototype.show = function (scene, color) {
  63984. if (!this._renderFunction) {
  63985. var ray = this.ray;
  63986. this._renderFunction = this._render.bind(this);
  63987. this._scene = scene;
  63988. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63989. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63990. this._scene.registerBeforeRender(this._renderFunction);
  63991. }
  63992. if (color) {
  63993. this._renderLine.color.copyFrom(color);
  63994. }
  63995. };
  63996. RayHelper.prototype.hide = function () {
  63997. if (this._renderFunction) {
  63998. this._scene.unregisterBeforeRender(this._renderFunction);
  63999. this._scene = null;
  64000. this._renderFunction = null;
  64001. this._renderLine.dispose();
  64002. this._renderLine = null;
  64003. this._renderPoints = null;
  64004. }
  64005. };
  64006. RayHelper.prototype._render = function () {
  64007. var ray = this.ray;
  64008. var point = this._renderPoints[1];
  64009. var len = Math.min(ray.length, 1000000);
  64010. point.copyFrom(ray.direction);
  64011. point.scaleInPlace(len);
  64012. point.addInPlace(ray.origin);
  64013. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64014. };
  64015. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64016. this._attachedToMesh = mesh;
  64017. var ray = this.ray;
  64018. if (!ray.direction) {
  64019. ray.direction = BABYLON.Vector3.Zero();
  64020. }
  64021. if (!ray.origin) {
  64022. ray.origin = BABYLON.Vector3.Zero();
  64023. }
  64024. if (length) {
  64025. ray.length = length;
  64026. }
  64027. if (!meshSpaceOrigin) {
  64028. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64029. }
  64030. if (!meshSpaceDirection) {
  64031. // -1 so that this will work with Mesh.lookAt
  64032. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64033. }
  64034. if (!this._meshSpaceDirection) {
  64035. this._meshSpaceDirection = meshSpaceDirection.clone();
  64036. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64037. }
  64038. else {
  64039. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64040. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64041. }
  64042. if (!this._updateToMeshFunction) {
  64043. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64044. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64045. }
  64046. this._updateToMesh();
  64047. };
  64048. RayHelper.prototype.detachFromMesh = function () {
  64049. if (this._attachedToMesh) {
  64050. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64051. this._attachedToMesh = null;
  64052. this._updateToMeshFunction = null;
  64053. }
  64054. };
  64055. RayHelper.prototype._updateToMesh = function () {
  64056. var ray = this.ray;
  64057. if (this._attachedToMesh._isDisposed) {
  64058. this.detachFromMesh();
  64059. return;
  64060. }
  64061. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64062. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64063. };
  64064. RayHelper.prototype.dispose = function () {
  64065. this.hide();
  64066. this.detachFromMesh();
  64067. this.ray = null;
  64068. };
  64069. return RayHelper;
  64070. }());
  64071. BABYLON.RayHelper = RayHelper;
  64072. })(BABYLON || (BABYLON = {}));
  64073. //# sourceMappingURL=babylon.rayHelper.js.map
  64074. var BABYLON;
  64075. (function (BABYLON) {
  64076. var DebugLayer = (function () {
  64077. function DebugLayer(scene) {
  64078. this._scene = scene;
  64079. }
  64080. /** Creates the inspector window. */
  64081. DebugLayer.prototype._createInspector = function (config) {
  64082. if (config === void 0) { config = {}; }
  64083. var popup = config.popup || false;
  64084. var initialTab = config.initialTab || 0;
  64085. var parentElement = config.parentElement || null;
  64086. if (!this._inspector) {
  64087. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64088. } // else nothing to do,; instance is already existing
  64089. };
  64090. DebugLayer.prototype.isVisible = function () {
  64091. if (!this._inspector) {
  64092. return false;
  64093. }
  64094. return true;
  64095. };
  64096. DebugLayer.prototype.hide = function () {
  64097. if (this._inspector) {
  64098. try {
  64099. this._inspector.dispose();
  64100. }
  64101. catch (e) {
  64102. // If the inspector has been removed directly from the inspector tool
  64103. }
  64104. this._inspector = null;
  64105. }
  64106. };
  64107. DebugLayer.prototype.show = function (config) {
  64108. if (config === void 0) { config = {}; }
  64109. if (typeof INSPECTOR == 'undefined') {
  64110. // Load inspector and add it to the DOM
  64111. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64112. }
  64113. else {
  64114. // Otherwise creates the inspector
  64115. this._createInspector(config);
  64116. }
  64117. };
  64118. // Get protocol used - http or https
  64119. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64120. return DebugLayer;
  64121. }());
  64122. BABYLON.DebugLayer = DebugLayer;
  64123. })(BABYLON || (BABYLON = {}));
  64124. //# sourceMappingURL=babylon.debugLayer.js.map
  64125. var BABYLON;
  64126. (function (BABYLON) {
  64127. var Debug;
  64128. (function (Debug) {
  64129. var PhysicsViewer = (function () {
  64130. function PhysicsViewer(scene) {
  64131. this._impostors = [];
  64132. this._meshes = [];
  64133. this._numMeshes = 0;
  64134. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64135. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  64136. }
  64137. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64138. var plugin = this._physicsEnginePlugin;
  64139. for (var i = 0; i < this._numMeshes; i++) {
  64140. if (this._impostors[i].isDisposed) {
  64141. this.hideImpostor(this._impostors[i--]);
  64142. }
  64143. else {
  64144. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  64145. }
  64146. }
  64147. };
  64148. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64149. for (var i = 0; i < this._numMeshes; i++) {
  64150. if (this._impostors[i] == impostor) {
  64151. return;
  64152. }
  64153. }
  64154. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64155. if (debugMesh) {
  64156. this._impostors[this._numMeshes] = impostor;
  64157. this._meshes[this._numMeshes] = debugMesh;
  64158. if (this._numMeshes === 0) {
  64159. this._renderFunction = this._updateDebugMeshes.bind(this);
  64160. this._scene.registerBeforeRender(this._renderFunction);
  64161. }
  64162. this._numMeshes++;
  64163. }
  64164. };
  64165. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64166. var removed = false;
  64167. for (var i = 0; i < this._numMeshes; i++) {
  64168. if (this._impostors[i] == impostor) {
  64169. this._scene.removeMesh(this._meshes[i]);
  64170. this._meshes[i].dispose();
  64171. this._numMeshes--;
  64172. if (this._numMeshes > 0) {
  64173. this._meshes[i] = this._meshes[this._numMeshes];
  64174. this._impostors[i] = this._impostors[this._numMeshes];
  64175. this._meshes[this._numMeshes] = null;
  64176. this._impostors[this._numMeshes] = null;
  64177. }
  64178. else {
  64179. this._meshes[0] = null;
  64180. this._impostors[0] = null;
  64181. }
  64182. removed = true;
  64183. break;
  64184. }
  64185. }
  64186. if (removed && this._numMeshes === 0) {
  64187. this._scene.unregisterBeforeRender(this._renderFunction);
  64188. }
  64189. };
  64190. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64191. if (!this._debugMaterial) {
  64192. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64193. this._debugMaterial.wireframe = true;
  64194. }
  64195. return this._debugMaterial;
  64196. };
  64197. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64198. if (!this._debugBoxMesh) {
  64199. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64200. this._debugBoxMesh.renderingGroupId = 1;
  64201. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64202. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64203. scene.removeMesh(this._debugBoxMesh);
  64204. }
  64205. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64206. };
  64207. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64208. if (!this._debugSphereMesh) {
  64209. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64210. this._debugSphereMesh.renderingGroupId = 1;
  64211. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64212. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64213. scene.removeMesh(this._debugSphereMesh);
  64214. }
  64215. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64216. };
  64217. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64218. var body = impostor.physicsBody;
  64219. var shape = body.shapes[0];
  64220. var mesh;
  64221. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64222. mesh = this._getDebugBoxMesh(scene);
  64223. impostor.getBoxSizeToRef(mesh.scaling);
  64224. }
  64225. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64226. mesh = this._getDebugSphereMesh(scene);
  64227. var radius = impostor.getRadius();
  64228. mesh.scaling.x = radius * 2;
  64229. mesh.scaling.y = radius * 2;
  64230. mesh.scaling.z = radius * 2;
  64231. }
  64232. return mesh;
  64233. };
  64234. PhysicsViewer.prototype.dispose = function () {
  64235. for (var i = 0; i < this._numMeshes; i++) {
  64236. this.hideImpostor(this._impostors[i]);
  64237. }
  64238. if (this._debugBoxMesh) {
  64239. this._debugBoxMesh.dispose();
  64240. }
  64241. if (this._debugSphereMesh) {
  64242. this._debugSphereMesh.dispose();
  64243. }
  64244. if (this._debugMaterial) {
  64245. this._debugMaterial.dispose();
  64246. }
  64247. this._impostors.length = 0;
  64248. this._scene = null;
  64249. this._physicsEnginePlugin = null;
  64250. };
  64251. return PhysicsViewer;
  64252. }());
  64253. Debug.PhysicsViewer = PhysicsViewer;
  64254. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64255. })(BABYLON || (BABYLON = {}));
  64256. //# sourceMappingURL=babylon.physicsViewer.js.map
  64257. var BABYLON;
  64258. (function (BABYLON) {
  64259. var BoundingBoxRenderer = (function () {
  64260. function BoundingBoxRenderer(scene) {
  64261. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64262. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64263. this.showBackLines = true;
  64264. this.renderList = new BABYLON.SmartArray(32);
  64265. this._vertexBuffers = {};
  64266. this._scene = scene;
  64267. }
  64268. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64269. if (this._colorShader) {
  64270. return;
  64271. }
  64272. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  64273. attributes: [BABYLON.VertexBuffer.PositionKind],
  64274. uniforms: ["world", "viewProjection", "color"]
  64275. });
  64276. var engine = this._scene.getEngine();
  64277. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64278. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64279. this._createIndexBuffer();
  64280. };
  64281. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64282. var engine = this._scene.getEngine();
  64283. 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]);
  64284. };
  64285. BoundingBoxRenderer.prototype._rebuild = function () {
  64286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  64287. this._createIndexBuffer();
  64288. };
  64289. BoundingBoxRenderer.prototype.reset = function () {
  64290. this.renderList.reset();
  64291. };
  64292. BoundingBoxRenderer.prototype.render = function () {
  64293. if (this.renderList.length === 0) {
  64294. return;
  64295. }
  64296. this._prepareRessources();
  64297. if (!this._colorShader.isReady()) {
  64298. return;
  64299. }
  64300. var engine = this._scene.getEngine();
  64301. engine.setDepthWrite(false);
  64302. this._colorShader._preBind();
  64303. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64304. var boundingBox = this.renderList.data[boundingBoxIndex];
  64305. var min = boundingBox.minimum;
  64306. var max = boundingBox.maximum;
  64307. var diff = max.subtract(min);
  64308. var median = min.add(diff.scale(0.5));
  64309. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64310. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64311. .multiply(boundingBox.getWorldMatrix());
  64312. // VBOs
  64313. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64314. if (this.showBackLines) {
  64315. // Back
  64316. engine.setDepthFunctionToGreaterOrEqual();
  64317. this._scene.resetCachedMaterial();
  64318. this._colorShader.setColor4("color", this.backColor.toColor4());
  64319. this._colorShader.bind(worldMatrix);
  64320. // Draw order
  64321. engine.draw(false, 0, 24);
  64322. }
  64323. // Front
  64324. engine.setDepthFunctionToLess();
  64325. this._scene.resetCachedMaterial();
  64326. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64327. this._colorShader.bind(worldMatrix);
  64328. // Draw order
  64329. engine.draw(false, 0, 24);
  64330. }
  64331. this._colorShader.unbind();
  64332. engine.setDepthFunctionToLessOrEqual();
  64333. engine.setDepthWrite(true);
  64334. };
  64335. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64336. this._prepareRessources();
  64337. if (!this._colorShader.isReady()) {
  64338. return;
  64339. }
  64340. var engine = this._scene.getEngine();
  64341. engine.setDepthWrite(false);
  64342. engine.setColorWrite(false);
  64343. this._colorShader._preBind();
  64344. var boundingBox = mesh._boundingInfo.boundingBox;
  64345. var min = boundingBox.minimum;
  64346. var max = boundingBox.maximum;
  64347. var diff = max.subtract(min);
  64348. var median = min.add(diff.scale(0.5));
  64349. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64350. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64351. .multiply(boundingBox.getWorldMatrix());
  64352. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64353. engine.setDepthFunctionToLess();
  64354. this._scene.resetCachedMaterial();
  64355. this._colorShader.bind(worldMatrix);
  64356. engine.draw(false, 0, 24);
  64357. this._colorShader.unbind();
  64358. engine.setDepthFunctionToLessOrEqual();
  64359. engine.setDepthWrite(true);
  64360. engine.setColorWrite(true);
  64361. };
  64362. BoundingBoxRenderer.prototype.dispose = function () {
  64363. if (!this._colorShader) {
  64364. return;
  64365. }
  64366. this.renderList.dispose();
  64367. this._colorShader.dispose();
  64368. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64369. if (buffer) {
  64370. buffer.dispose();
  64371. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64372. }
  64373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64374. };
  64375. return BoundingBoxRenderer;
  64376. }());
  64377. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64378. })(BABYLON || (BABYLON = {}));
  64379. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64380. var BABYLON;
  64381. (function (BABYLON) {
  64382. var MorphTarget = (function () {
  64383. function MorphTarget(name, influence) {
  64384. if (influence === void 0) { influence = 0; }
  64385. this.name = name;
  64386. this.animations = new Array();
  64387. this.onInfluenceChanged = new BABYLON.Observable();
  64388. this.influence = influence;
  64389. }
  64390. Object.defineProperty(MorphTarget.prototype, "influence", {
  64391. get: function () {
  64392. return this._influence;
  64393. },
  64394. set: function (influence) {
  64395. if (this._influence === influence) {
  64396. return;
  64397. }
  64398. var previous = this._influence;
  64399. this._influence = influence;
  64400. if (this.onInfluenceChanged.hasObservers) {
  64401. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  64402. }
  64403. },
  64404. enumerable: true,
  64405. configurable: true
  64406. });
  64407. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  64408. get: function () {
  64409. return this._normals !== undefined;
  64410. },
  64411. enumerable: true,
  64412. configurable: true
  64413. });
  64414. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  64415. get: function () {
  64416. return this._tangents !== undefined;
  64417. },
  64418. enumerable: true,
  64419. configurable: true
  64420. });
  64421. MorphTarget.prototype.setPositions = function (data) {
  64422. this._positions = new Float32Array(data);
  64423. };
  64424. MorphTarget.prototype.getPositions = function () {
  64425. return this._positions;
  64426. };
  64427. MorphTarget.prototype.setNormals = function (data) {
  64428. this._normals = new Float32Array(data);
  64429. };
  64430. MorphTarget.prototype.getNormals = function () {
  64431. return this._normals;
  64432. };
  64433. MorphTarget.prototype.setTangents = function (data) {
  64434. this._tangents = new Float32Array(data);
  64435. };
  64436. MorphTarget.prototype.getTangents = function () {
  64437. return this._tangents;
  64438. };
  64439. /**
  64440. * Serializes the current target into a Serialization object.
  64441. * Returns the serialized object.
  64442. */
  64443. MorphTarget.prototype.serialize = function () {
  64444. var serializationObject = {};
  64445. serializationObject.name = this.name;
  64446. serializationObject.influence = this.influence;
  64447. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  64448. if (this.hasNormals) {
  64449. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  64450. }
  64451. if (this.hasTangents) {
  64452. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  64453. }
  64454. return serializationObject;
  64455. };
  64456. // Statics
  64457. MorphTarget.Parse = function (serializationObject) {
  64458. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  64459. result.setPositions(serializationObject.positions);
  64460. if (serializationObject.normals) {
  64461. result.setNormals(serializationObject.normals);
  64462. }
  64463. if (serializationObject.tangents) {
  64464. result.setTangents(serializationObject.tangents);
  64465. }
  64466. return result;
  64467. };
  64468. MorphTarget.FromMesh = function (mesh, name, influence) {
  64469. if (!name) {
  64470. name = mesh.name;
  64471. }
  64472. var result = new MorphTarget(name, influence);
  64473. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  64474. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64475. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  64476. }
  64477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  64478. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  64479. }
  64480. return result;
  64481. };
  64482. return MorphTarget;
  64483. }());
  64484. BABYLON.MorphTarget = MorphTarget;
  64485. })(BABYLON || (BABYLON = {}));
  64486. //# sourceMappingURL=babylon.morphTarget.js.map
  64487. var BABYLON;
  64488. (function (BABYLON) {
  64489. var MorphTargetManager = (function () {
  64490. function MorphTargetManager(scene) {
  64491. this._targets = new Array();
  64492. this._targetObservable = new Array();
  64493. this._activeTargets = new BABYLON.SmartArray(16);
  64494. this._supportsNormals = false;
  64495. this._supportsTangents = false;
  64496. this._vertexCount = 0;
  64497. this._uniqueId = 0;
  64498. this._tempInfluences = new Array();
  64499. if (!scene) {
  64500. scene = BABYLON.Engine.LastCreatedScene;
  64501. }
  64502. this._scene = scene;
  64503. this._scene.morphTargetManagers.push(this);
  64504. this._uniqueId = scene.getUniqueId();
  64505. }
  64506. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  64507. get: function () {
  64508. return this._uniqueId;
  64509. },
  64510. enumerable: true,
  64511. configurable: true
  64512. });
  64513. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  64514. get: function () {
  64515. return this._vertexCount;
  64516. },
  64517. enumerable: true,
  64518. configurable: true
  64519. });
  64520. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  64521. get: function () {
  64522. return this._supportsNormals;
  64523. },
  64524. enumerable: true,
  64525. configurable: true
  64526. });
  64527. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  64528. get: function () {
  64529. return this._supportsTangents;
  64530. },
  64531. enumerable: true,
  64532. configurable: true
  64533. });
  64534. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  64535. get: function () {
  64536. return this._targets.length;
  64537. },
  64538. enumerable: true,
  64539. configurable: true
  64540. });
  64541. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  64542. get: function () {
  64543. return this._activeTargets.length;
  64544. },
  64545. enumerable: true,
  64546. configurable: true
  64547. });
  64548. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  64549. get: function () {
  64550. return this._influences;
  64551. },
  64552. enumerable: true,
  64553. configurable: true
  64554. });
  64555. MorphTargetManager.prototype.getActiveTarget = function (index) {
  64556. return this._activeTargets.data[index];
  64557. };
  64558. MorphTargetManager.prototype.getTarget = function (index) {
  64559. return this._targets[index];
  64560. };
  64561. MorphTargetManager.prototype.addTarget = function (target) {
  64562. var _this = this;
  64563. if (this._vertexCount) {
  64564. if (this._vertexCount !== target.getPositions().length / 3) {
  64565. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  64566. return;
  64567. }
  64568. }
  64569. this._targets.push(target);
  64570. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  64571. _this._syncActiveTargets(needUpdate);
  64572. }));
  64573. this._syncActiveTargets(true);
  64574. };
  64575. MorphTargetManager.prototype.removeTarget = function (target) {
  64576. var index = this._targets.indexOf(target);
  64577. if (index >= 0) {
  64578. this._targets.splice(index, 1);
  64579. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  64580. this._vertexCount = 0;
  64581. this._syncActiveTargets(true);
  64582. }
  64583. };
  64584. /**
  64585. * Serializes the current manager into a Serialization object.
  64586. * Returns the serialized object.
  64587. */
  64588. MorphTargetManager.prototype.serialize = function () {
  64589. var serializationObject = {};
  64590. serializationObject.id = this.uniqueId;
  64591. serializationObject.targets = [];
  64592. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64593. var target = _a[_i];
  64594. serializationObject.targets.push(target.serialize());
  64595. }
  64596. return serializationObject;
  64597. };
  64598. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  64599. this._syncActiveTargets(needUpdate);
  64600. };
  64601. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  64602. var influenceCount = 0;
  64603. this._activeTargets.reset();
  64604. this._supportsNormals = true;
  64605. this._supportsTangents = true;
  64606. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64607. var target = _a[_i];
  64608. if (target.influence > 0) {
  64609. this._activeTargets.push(target);
  64610. this._tempInfluences[influenceCount++] = target.influence;
  64611. this._supportsNormals = this._supportsNormals && target.hasNormals;
  64612. this._supportsTangents = this._supportsTangents && target.hasTangents;
  64613. if (this._vertexCount === 0) {
  64614. this._vertexCount = target.getPositions().length / 3;
  64615. }
  64616. }
  64617. }
  64618. if (!this._influences || this._influences.length !== influenceCount) {
  64619. this._influences = new Float32Array(influenceCount);
  64620. }
  64621. for (var index = 0; index < influenceCount; index++) {
  64622. this._influences[index] = this._tempInfluences[index];
  64623. }
  64624. if (needUpdate) {
  64625. // Flag meshes as dirty to resync with the active targets
  64626. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  64627. var mesh = _c[_b];
  64628. if (mesh.morphTargetManager === this) {
  64629. mesh._syncGeometryWithMorphTargetManager();
  64630. }
  64631. }
  64632. }
  64633. };
  64634. // Statics
  64635. MorphTargetManager.Parse = function (serializationObject, scene) {
  64636. var result = new MorphTargetManager(scene);
  64637. result._uniqueId = serializationObject.id;
  64638. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  64639. var targetData = _a[_i];
  64640. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  64641. }
  64642. return result;
  64643. };
  64644. return MorphTargetManager;
  64645. }());
  64646. BABYLON.MorphTargetManager = MorphTargetManager;
  64647. })(BABYLON || (BABYLON = {}));
  64648. //# sourceMappingURL=babylon.morphTargetManager.js.map
  64649. var BABYLON;
  64650. (function (BABYLON) {
  64651. /**
  64652. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  64653. * It can help converting any input color in a desired output one. This can then be used to create effects
  64654. * from sepia, black and white to sixties or futuristic rendering...
  64655. *
  64656. * The only supported format is currently 3dl.
  64657. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  64658. */
  64659. var ColorGradingTexture = (function (_super) {
  64660. __extends(ColorGradingTexture, _super);
  64661. /**
  64662. * Instantiates a ColorGradingTexture from the following parameters.
  64663. *
  64664. * @param url The location of the color gradind data (currently only supporting 3dl)
  64665. * @param scene The scene the texture will be used in
  64666. */
  64667. function ColorGradingTexture(url, scene) {
  64668. var _this = _super.call(this, scene) || this;
  64669. if (!url) {
  64670. return _this;
  64671. }
  64672. _this._textureMatrix = BABYLON.Matrix.Identity();
  64673. _this.name = url;
  64674. _this.url = url;
  64675. _this.hasAlpha = false;
  64676. _this.isCube = false;
  64677. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64678. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64679. _this.anisotropicFilteringLevel = 1;
  64680. _this._texture = _this._getFromCache(url, true);
  64681. if (!_this._texture) {
  64682. if (!scene.useDelayedTextureLoading) {
  64683. _this.loadTexture();
  64684. }
  64685. else {
  64686. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64687. }
  64688. }
  64689. return _this;
  64690. }
  64691. /**
  64692. * Returns the texture matrix used in most of the material.
  64693. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  64694. */
  64695. ColorGradingTexture.prototype.getTextureMatrix = function () {
  64696. return this._textureMatrix;
  64697. };
  64698. /**
  64699. * Occurs when the file being loaded is a .3dl LUT file.
  64700. */
  64701. ColorGradingTexture.prototype.load3dlTexture = function () {
  64702. var _this = this;
  64703. var mipLevels = 0;
  64704. var floatArrayView = null;
  64705. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64706. this._texture = texture;
  64707. var callback = function (text) {
  64708. var data;
  64709. var tempData;
  64710. var line;
  64711. var lines = text.split('\n');
  64712. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  64713. var maxColor = 0;
  64714. for (var i = 0; i < lines.length; i++) {
  64715. line = lines[i];
  64716. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  64717. continue;
  64718. if (line.indexOf('#') === 0)
  64719. continue;
  64720. var words = line.split(" ");
  64721. if (size === 0) {
  64722. // Number of space + one
  64723. size = words.length;
  64724. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  64725. tempData = new Float32Array(size * size * size * 4);
  64726. continue;
  64727. }
  64728. if (size != 0) {
  64729. var r = Math.max(parseInt(words[0]), 0);
  64730. var g = Math.max(parseInt(words[1]), 0);
  64731. var b = Math.max(parseInt(words[2]), 0);
  64732. maxColor = Math.max(r, maxColor);
  64733. maxColor = Math.max(g, maxColor);
  64734. maxColor = Math.max(b, maxColor);
  64735. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  64736. tempData[pixelStorageIndex + 0] = r;
  64737. tempData[pixelStorageIndex + 1] = g;
  64738. tempData[pixelStorageIndex + 2] = b;
  64739. pixelIndexSlice++;
  64740. if (pixelIndexSlice % size == 0) {
  64741. pixelIndexH++;
  64742. pixelIndexSlice = 0;
  64743. if (pixelIndexH % size == 0) {
  64744. pixelIndexW++;
  64745. pixelIndexH = 0;
  64746. }
  64747. }
  64748. }
  64749. }
  64750. for (var i = 0; i < tempData.length; i++) {
  64751. if (i > 0 && (i + 1) % 4 === 0) {
  64752. data[i] = 255;
  64753. }
  64754. else {
  64755. var value = tempData[i];
  64756. data[i] = (value / maxColor * 255);
  64757. }
  64758. }
  64759. texture.updateSize(size * size, size);
  64760. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  64761. };
  64762. BABYLON.Tools.LoadFile(this.url, callback);
  64763. return this._texture;
  64764. };
  64765. /**
  64766. * Starts the loading process of the texture.
  64767. */
  64768. ColorGradingTexture.prototype.loadTexture = function () {
  64769. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  64770. this.load3dlTexture();
  64771. }
  64772. };
  64773. /**
  64774. * Clones the color gradind texture.
  64775. */
  64776. ColorGradingTexture.prototype.clone = function () {
  64777. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  64778. // Base texture
  64779. newTexture.level = this.level;
  64780. return newTexture;
  64781. };
  64782. /**
  64783. * Called during delayed load for textures.
  64784. */
  64785. ColorGradingTexture.prototype.delayLoad = function () {
  64786. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64787. return;
  64788. }
  64789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64790. this._texture = this._getFromCache(this.url, true);
  64791. if (!this._texture) {
  64792. this.loadTexture();
  64793. }
  64794. };
  64795. /**
  64796. * Parses a color grading texture serialized by Babylon.
  64797. * @param parsedTexture The texture information being parsedTexture
  64798. * @param scene The scene to load the texture in
  64799. * @param rootUrl The root url of the data assets to load
  64800. * @return A color gradind texture
  64801. */
  64802. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64803. var texture = null;
  64804. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64805. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  64806. texture.name = parsedTexture.name;
  64807. texture.level = parsedTexture.level;
  64808. }
  64809. return texture;
  64810. };
  64811. /**
  64812. * Serializes the LUT texture to json format.
  64813. */
  64814. ColorGradingTexture.prototype.serialize = function () {
  64815. if (!this.name) {
  64816. return null;
  64817. }
  64818. var serializationObject = {};
  64819. serializationObject.name = this.name;
  64820. serializationObject.level = this.level;
  64821. serializationObject.customType = "BABYLON.ColorGradingTexture";
  64822. return serializationObject;
  64823. };
  64824. /**
  64825. * Empty line regex stored for GC.
  64826. */
  64827. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  64828. return ColorGradingTexture;
  64829. }(BABYLON.BaseTexture));
  64830. BABYLON.ColorGradingTexture = ColorGradingTexture;
  64831. })(BABYLON || (BABYLON = {}));
  64832. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  64833. var BABYLON;
  64834. (function (BABYLON) {
  64835. /**
  64836. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  64837. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  64838. * 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;
  64839. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  64840. */
  64841. var ColorCurves = (function () {
  64842. function ColorCurves() {
  64843. this._dirty = true;
  64844. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  64845. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  64846. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  64847. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  64848. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  64849. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  64850. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  64851. this._globalHue = 30;
  64852. this._globalDensity = 0;
  64853. this._globalSaturation = 0;
  64854. this._globalExposure = 0;
  64855. this._highlightsHue = 30;
  64856. this._highlightsDensity = 0;
  64857. this._highlightsSaturation = 0;
  64858. this._highlightsExposure = 0;
  64859. this._midtonesHue = 30;
  64860. this._midtonesDensity = 0;
  64861. this._midtonesSaturation = 0;
  64862. this._midtonesExposure = 0;
  64863. this._shadowsHue = 30;
  64864. this._shadowsDensity = 0;
  64865. this._shadowsSaturation = 0;
  64866. this._shadowsExposure = 0;
  64867. }
  64868. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  64869. /**
  64870. * Gets the global Hue value.
  64871. * 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).
  64872. */
  64873. get: function () {
  64874. return this._globalHue;
  64875. },
  64876. /**
  64877. * Sets the global Hue value.
  64878. * 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).
  64879. */
  64880. set: function (value) {
  64881. this._globalHue = value;
  64882. this._dirty = true;
  64883. },
  64884. enumerable: true,
  64885. configurable: true
  64886. });
  64887. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  64888. /**
  64889. * Gets the global Density value.
  64890. * 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.
  64891. * Values less than zero provide a filter of opposite hue.
  64892. */
  64893. get: function () {
  64894. return this._globalDensity;
  64895. },
  64896. /**
  64897. * Sets the global Density value.
  64898. * 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.
  64899. * Values less than zero provide a filter of opposite hue.
  64900. */
  64901. set: function (value) {
  64902. this._globalDensity = value;
  64903. this._dirty = true;
  64904. },
  64905. enumerable: true,
  64906. configurable: true
  64907. });
  64908. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  64909. /**
  64910. * Gets the global Saturation value.
  64911. * 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.
  64912. */
  64913. get: function () {
  64914. return this._globalSaturation;
  64915. },
  64916. /**
  64917. * Sets the global Saturation value.
  64918. * 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.
  64919. */
  64920. set: function (value) {
  64921. this._globalSaturation = value;
  64922. this._dirty = true;
  64923. },
  64924. enumerable: true,
  64925. configurable: true
  64926. });
  64927. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  64928. /**
  64929. * Gets the highlights Hue value.
  64930. * 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).
  64931. */
  64932. get: function () {
  64933. return this._highlightsHue;
  64934. },
  64935. /**
  64936. * Sets the highlights Hue value.
  64937. * 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).
  64938. */
  64939. set: function (value) {
  64940. this._highlightsHue = value;
  64941. this._dirty = true;
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  64947. /**
  64948. * Gets the highlights Density value.
  64949. * 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.
  64950. * Values less than zero provide a filter of opposite hue.
  64951. */
  64952. get: function () {
  64953. return this._highlightsDensity;
  64954. },
  64955. /**
  64956. * Sets the highlights Density value.
  64957. * 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.
  64958. * Values less than zero provide a filter of opposite hue.
  64959. */
  64960. set: function (value) {
  64961. this._highlightsDensity = value;
  64962. this._dirty = true;
  64963. },
  64964. enumerable: true,
  64965. configurable: true
  64966. });
  64967. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  64968. /**
  64969. * Gets the highlights Saturation value.
  64970. * 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.
  64971. */
  64972. get: function () {
  64973. return this._highlightsSaturation;
  64974. },
  64975. /**
  64976. * Sets the highlights Saturation value.
  64977. * 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.
  64978. */
  64979. set: function (value) {
  64980. this._highlightsSaturation = value;
  64981. this._dirty = true;
  64982. },
  64983. enumerable: true,
  64984. configurable: true
  64985. });
  64986. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  64987. /**
  64988. * Gets the highlights Exposure value.
  64989. * 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.
  64990. */
  64991. get: function () {
  64992. return this._highlightsExposure;
  64993. },
  64994. /**
  64995. * Sets the highlights Exposure value.
  64996. * 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.
  64997. */
  64998. set: function (value) {
  64999. this._highlightsExposure = value;
  65000. this._dirty = true;
  65001. },
  65002. enumerable: true,
  65003. configurable: true
  65004. });
  65005. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  65006. /**
  65007. * Gets the midtones Hue value.
  65008. * 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).
  65009. */
  65010. get: function () {
  65011. return this._midtonesHue;
  65012. },
  65013. /**
  65014. * Sets the midtones Hue value.
  65015. * 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).
  65016. */
  65017. set: function (value) {
  65018. this._midtonesHue = value;
  65019. this._dirty = true;
  65020. },
  65021. enumerable: true,
  65022. configurable: true
  65023. });
  65024. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  65025. /**
  65026. * Gets the midtones Density value.
  65027. * 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.
  65028. * Values less than zero provide a filter of opposite hue.
  65029. */
  65030. get: function () {
  65031. return this._midtonesDensity;
  65032. },
  65033. /**
  65034. * Sets the midtones Density value.
  65035. * 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.
  65036. * Values less than zero provide a filter of opposite hue.
  65037. */
  65038. set: function (value) {
  65039. this._midtonesDensity = value;
  65040. this._dirty = true;
  65041. },
  65042. enumerable: true,
  65043. configurable: true
  65044. });
  65045. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  65046. /**
  65047. * Gets the midtones Saturation value.
  65048. * 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.
  65049. */
  65050. get: function () {
  65051. return this._midtonesSaturation;
  65052. },
  65053. /**
  65054. * Sets the midtones Saturation value.
  65055. * 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.
  65056. */
  65057. set: function (value) {
  65058. this._midtonesSaturation = value;
  65059. this._dirty = true;
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  65065. /**
  65066. * Gets the midtones Exposure value.
  65067. * 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.
  65068. */
  65069. get: function () {
  65070. return this._midtonesExposure;
  65071. },
  65072. /**
  65073. * Sets the midtones Exposure value.
  65074. * 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.
  65075. */
  65076. set: function (value) {
  65077. this._midtonesExposure = value;
  65078. this._dirty = true;
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  65084. /**
  65085. * Gets the shadows Hue value.
  65086. * 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).
  65087. */
  65088. get: function () {
  65089. return this._shadowsHue;
  65090. },
  65091. /**
  65092. * Sets the shadows Hue value.
  65093. * 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).
  65094. */
  65095. set: function (value) {
  65096. this._shadowsHue = value;
  65097. this._dirty = true;
  65098. },
  65099. enumerable: true,
  65100. configurable: true
  65101. });
  65102. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  65103. /**
  65104. * Gets the shadows Density value.
  65105. * 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.
  65106. * Values less than zero provide a filter of opposite hue.
  65107. */
  65108. get: function () {
  65109. return this._shadowsDensity;
  65110. },
  65111. /**
  65112. * Sets the shadows Density value.
  65113. * 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.
  65114. * Values less than zero provide a filter of opposite hue.
  65115. */
  65116. set: function (value) {
  65117. this._shadowsDensity = value;
  65118. this._dirty = true;
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  65124. /**
  65125. * Gets the shadows Saturation value.
  65126. * 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.
  65127. */
  65128. get: function () {
  65129. return this._shadowsSaturation;
  65130. },
  65131. /**
  65132. * Sets the shadows Saturation value.
  65133. * 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.
  65134. */
  65135. set: function (value) {
  65136. this._shadowsSaturation = value;
  65137. this._dirty = true;
  65138. },
  65139. enumerable: true,
  65140. configurable: true
  65141. });
  65142. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  65143. /**
  65144. * Gets the shadows Exposure value.
  65145. * 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.
  65146. */
  65147. get: function () {
  65148. return this._shadowsExposure;
  65149. },
  65150. /**
  65151. * Sets the shadows Exposure value.
  65152. * 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.
  65153. */
  65154. set: function (value) {
  65155. this._shadowsExposure = value;
  65156. this._dirty = true;
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. ColorCurves.prototype.getClassName = function () {
  65162. return "ColorCurves";
  65163. };
  65164. /**
  65165. * Binds the color curves to the shader.
  65166. * @param colorCurves The color curve to bind
  65167. * @param effect The effect to bind to
  65168. */
  65169. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  65170. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  65171. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  65172. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  65173. if (colorCurves._dirty) {
  65174. colorCurves._dirty = false;
  65175. // Fill in global info.
  65176. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  65177. // Compute highlights info.
  65178. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  65179. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  65180. // Compute midtones info.
  65181. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  65182. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  65183. // Compute shadows info.
  65184. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  65185. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  65186. // Compute deltas (neutral is midtones).
  65187. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  65188. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  65189. }
  65190. if (effect) {
  65191. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  65192. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  65193. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  65194. }
  65195. };
  65196. /**
  65197. * Prepare the list of uniforms associated with the ColorCurves effects.
  65198. * @param uniformsList The list of uniforms used in the effect
  65199. */
  65200. ColorCurves.PrepareUniforms = function (uniformsList) {
  65201. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  65202. };
  65203. /**
  65204. * Returns color grading data based on a hue, density, saturation and exposure value.
  65205. * @param filterHue The hue of the color filter.
  65206. * @param filterDensity The density of the color filter.
  65207. * @param saturation The saturation.
  65208. * @param exposure The exposure.
  65209. * @param result The result data container.
  65210. */
  65211. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  65212. if (hue == null) {
  65213. return;
  65214. }
  65215. hue = ColorCurves.clamp(hue, 0, 360);
  65216. density = ColorCurves.clamp(density, -100, 100);
  65217. saturation = ColorCurves.clamp(saturation, -100, 100);
  65218. exposure = ColorCurves.clamp(exposure, -100, 100);
  65219. // Remap the slider/config filter density with non-linear mapping and also scale by half
  65220. // so that the maximum filter density is only 50% control. This provides fine control
  65221. // for small values and reasonable range.
  65222. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  65223. density *= 0.5;
  65224. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  65225. if (density < 0) {
  65226. density *= -1;
  65227. hue = (hue + 180) % 360;
  65228. }
  65229. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  65230. result.scaleToRef(2, result);
  65231. result.a = 1 + 0.01 * saturation;
  65232. };
  65233. /**
  65234. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  65235. * @param value The input slider value in range [-100,100].
  65236. * @returns Adjusted value.
  65237. */
  65238. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  65239. value /= 100;
  65240. var x = Math.abs(value);
  65241. x = Math.pow(x, 2);
  65242. if (value < 0) {
  65243. x *= -1;
  65244. }
  65245. x *= 100;
  65246. return x;
  65247. };
  65248. /**
  65249. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  65250. * @param hue The hue (H) input.
  65251. * @param saturation The saturation (S) input.
  65252. * @param brightness The brightness (B) input.
  65253. * @result An RGBA color represented as Vector4.
  65254. */
  65255. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  65256. var h = ColorCurves.clamp(hue, 0, 360);
  65257. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  65258. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  65259. if (s === 0) {
  65260. result.r = v;
  65261. result.g = v;
  65262. result.b = v;
  65263. }
  65264. else {
  65265. // sector 0 to 5
  65266. h /= 60;
  65267. var i = Math.floor(h);
  65268. // fractional part of h
  65269. var f = h - i;
  65270. var p = v * (1 - s);
  65271. var q = v * (1 - s * f);
  65272. var t = v * (1 - s * (1 - f));
  65273. switch (i) {
  65274. case 0:
  65275. result.r = v;
  65276. result.g = t;
  65277. result.b = p;
  65278. break;
  65279. case 1:
  65280. result.r = q;
  65281. result.g = v;
  65282. result.b = p;
  65283. break;
  65284. case 2:
  65285. result.r = p;
  65286. result.g = v;
  65287. result.b = t;
  65288. break;
  65289. case 3:
  65290. result.r = p;
  65291. result.g = q;
  65292. result.b = v;
  65293. break;
  65294. case 4:
  65295. result.r = t;
  65296. result.g = p;
  65297. result.b = v;
  65298. break;
  65299. default:// case 5:
  65300. result.r = v;
  65301. result.g = p;
  65302. result.b = q;
  65303. break;
  65304. }
  65305. }
  65306. result.a = 1;
  65307. };
  65308. /**
  65309. * Returns a value clamped between min and max
  65310. * @param value The value to clamp
  65311. * @param min The minimum of value
  65312. * @param max The maximum of value
  65313. * @returns The clamped value.
  65314. */
  65315. ColorCurves.clamp = function (value, min, max) {
  65316. return Math.min(Math.max(value, min), max);
  65317. };
  65318. /**
  65319. * Clones the current color curve instance.
  65320. * @return The cloned curves
  65321. */
  65322. ColorCurves.prototype.clone = function () {
  65323. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  65324. };
  65325. /**
  65326. * Serializes the current color curve instance to a json representation.
  65327. * @return a JSON representation
  65328. */
  65329. ColorCurves.prototype.serialize = function () {
  65330. return BABYLON.SerializationHelper.Serialize(this);
  65331. };
  65332. /**
  65333. * Parses the color curve from a json representation.
  65334. * @param source the JSON source to parse
  65335. * @return The parsed curves
  65336. */
  65337. ColorCurves.Parse = function (source) {
  65338. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  65339. };
  65340. __decorate([
  65341. BABYLON.serialize()
  65342. ], ColorCurves.prototype, "_globalHue", void 0);
  65343. __decorate([
  65344. BABYLON.serialize()
  65345. ], ColorCurves.prototype, "_globalDensity", void 0);
  65346. __decorate([
  65347. BABYLON.serialize()
  65348. ], ColorCurves.prototype, "_globalSaturation", void 0);
  65349. __decorate([
  65350. BABYLON.serialize()
  65351. ], ColorCurves.prototype, "_globalExposure", void 0);
  65352. __decorate([
  65353. BABYLON.serialize()
  65354. ], ColorCurves.prototype, "_highlightsHue", void 0);
  65355. __decorate([
  65356. BABYLON.serialize()
  65357. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  65358. __decorate([
  65359. BABYLON.serialize()
  65360. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  65361. __decorate([
  65362. BABYLON.serialize()
  65363. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  65364. __decorate([
  65365. BABYLON.serialize()
  65366. ], ColorCurves.prototype, "_midtonesHue", void 0);
  65367. __decorate([
  65368. BABYLON.serialize()
  65369. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  65370. __decorate([
  65371. BABYLON.serialize()
  65372. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  65373. __decorate([
  65374. BABYLON.serialize()
  65375. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  65376. return ColorCurves;
  65377. }());
  65378. BABYLON.ColorCurves = ColorCurves;
  65379. })(BABYLON || (BABYLON = {}));
  65380. //# sourceMappingURL=babylon.colorCurves.js.map
  65381. var BABYLON;
  65382. (function (BABYLON) {
  65383. var Octree = (function () {
  65384. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  65385. if (maxDepth === void 0) { maxDepth = 2; }
  65386. this.maxDepth = maxDepth;
  65387. this.dynamicContent = new Array();
  65388. this._maxBlockCapacity = maxBlockCapacity || 64;
  65389. this._selectionContent = new BABYLON.SmartArray(1024);
  65390. this._creationFunc = creationFunc;
  65391. }
  65392. // Methods
  65393. Octree.prototype.update = function (worldMin, worldMax, entries) {
  65394. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  65395. };
  65396. Octree.prototype.addMesh = function (entry) {
  65397. for (var index = 0; index < this.blocks.length; index++) {
  65398. var block = this.blocks[index];
  65399. block.addEntry(entry);
  65400. }
  65401. };
  65402. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  65403. this._selectionContent.reset();
  65404. for (var index = 0; index < this.blocks.length; index++) {
  65405. var block = this.blocks[index];
  65406. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  65407. }
  65408. if (allowDuplicate) {
  65409. this._selectionContent.concat(this.dynamicContent);
  65410. }
  65411. else {
  65412. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65413. }
  65414. return this._selectionContent;
  65415. };
  65416. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  65417. this._selectionContent.reset();
  65418. for (var index = 0; index < this.blocks.length; index++) {
  65419. var block = this.blocks[index];
  65420. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  65421. }
  65422. if (allowDuplicate) {
  65423. this._selectionContent.concat(this.dynamicContent);
  65424. }
  65425. else {
  65426. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65427. }
  65428. return this._selectionContent;
  65429. };
  65430. Octree.prototype.intersectsRay = function (ray) {
  65431. this._selectionContent.reset();
  65432. for (var index = 0; index < this.blocks.length; index++) {
  65433. var block = this.blocks[index];
  65434. block.intersectsRay(ray, this._selectionContent);
  65435. }
  65436. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65437. return this._selectionContent;
  65438. };
  65439. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  65440. target.blocks = new Array();
  65441. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  65442. // Segmenting space
  65443. for (var x = 0; x < 2; x++) {
  65444. for (var y = 0; y < 2; y++) {
  65445. for (var z = 0; z < 2; z++) {
  65446. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  65447. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  65448. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  65449. block.addEntries(entries);
  65450. target.blocks.push(block);
  65451. }
  65452. }
  65453. }
  65454. };
  65455. Octree.CreationFuncForMeshes = function (entry, block) {
  65456. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65457. block.entries.push(entry);
  65458. }
  65459. };
  65460. Octree.CreationFuncForSubMeshes = function (entry, block) {
  65461. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65462. block.entries.push(entry);
  65463. }
  65464. };
  65465. return Octree;
  65466. }());
  65467. BABYLON.Octree = Octree;
  65468. })(BABYLON || (BABYLON = {}));
  65469. //# sourceMappingURL=babylon.octree.js.map
  65470. var BABYLON;
  65471. (function (BABYLON) {
  65472. var OctreeBlock = (function () {
  65473. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  65474. this.entries = new Array();
  65475. this._boundingVectors = new Array();
  65476. this._capacity = capacity;
  65477. this._depth = depth;
  65478. this._maxDepth = maxDepth;
  65479. this._creationFunc = creationFunc;
  65480. this._minPoint = minPoint;
  65481. this._maxPoint = maxPoint;
  65482. this._boundingVectors.push(minPoint.clone());
  65483. this._boundingVectors.push(maxPoint.clone());
  65484. this._boundingVectors.push(minPoint.clone());
  65485. this._boundingVectors[2].x = maxPoint.x;
  65486. this._boundingVectors.push(minPoint.clone());
  65487. this._boundingVectors[3].y = maxPoint.y;
  65488. this._boundingVectors.push(minPoint.clone());
  65489. this._boundingVectors[4].z = maxPoint.z;
  65490. this._boundingVectors.push(maxPoint.clone());
  65491. this._boundingVectors[5].z = minPoint.z;
  65492. this._boundingVectors.push(maxPoint.clone());
  65493. this._boundingVectors[6].x = minPoint.x;
  65494. this._boundingVectors.push(maxPoint.clone());
  65495. this._boundingVectors[7].y = minPoint.y;
  65496. }
  65497. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  65498. // Property
  65499. get: function () {
  65500. return this._capacity;
  65501. },
  65502. enumerable: true,
  65503. configurable: true
  65504. });
  65505. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  65506. get: function () {
  65507. return this._minPoint;
  65508. },
  65509. enumerable: true,
  65510. configurable: true
  65511. });
  65512. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  65513. get: function () {
  65514. return this._maxPoint;
  65515. },
  65516. enumerable: true,
  65517. configurable: true
  65518. });
  65519. // Methods
  65520. OctreeBlock.prototype.addEntry = function (entry) {
  65521. if (this.blocks) {
  65522. for (var index = 0; index < this.blocks.length; index++) {
  65523. var block = this.blocks[index];
  65524. block.addEntry(entry);
  65525. }
  65526. return;
  65527. }
  65528. this._creationFunc(entry, this);
  65529. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  65530. this.createInnerBlocks();
  65531. }
  65532. };
  65533. OctreeBlock.prototype.addEntries = function (entries) {
  65534. for (var index = 0; index < entries.length; index++) {
  65535. var mesh = entries[index];
  65536. this.addEntry(mesh);
  65537. }
  65538. };
  65539. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  65540. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  65541. if (this.blocks) {
  65542. for (var index = 0; index < this.blocks.length; index++) {
  65543. var block = this.blocks[index];
  65544. block.select(frustumPlanes, selection, allowDuplicate);
  65545. }
  65546. return;
  65547. }
  65548. if (allowDuplicate) {
  65549. selection.concat(this.entries);
  65550. }
  65551. else {
  65552. selection.concatWithNoDuplicate(this.entries);
  65553. }
  65554. }
  65555. };
  65556. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  65557. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  65558. if (this.blocks) {
  65559. for (var index = 0; index < this.blocks.length; index++) {
  65560. var block = this.blocks[index];
  65561. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  65562. }
  65563. return;
  65564. }
  65565. if (allowDuplicate) {
  65566. selection.concat(this.entries);
  65567. }
  65568. else {
  65569. selection.concatWithNoDuplicate(this.entries);
  65570. }
  65571. }
  65572. };
  65573. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  65574. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  65575. if (this.blocks) {
  65576. for (var index = 0; index < this.blocks.length; index++) {
  65577. var block = this.blocks[index];
  65578. block.intersectsRay(ray, selection);
  65579. }
  65580. return;
  65581. }
  65582. selection.concatWithNoDuplicate(this.entries);
  65583. }
  65584. };
  65585. OctreeBlock.prototype.createInnerBlocks = function () {
  65586. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  65587. };
  65588. return OctreeBlock;
  65589. }());
  65590. BABYLON.OctreeBlock = OctreeBlock;
  65591. })(BABYLON || (BABYLON = {}));
  65592. //# sourceMappingURL=babylon.octreeBlock.js.map
  65593. var BABYLON;
  65594. (function (BABYLON) {
  65595. var SIMDVector3 = (function () {
  65596. function SIMDVector3() {
  65597. }
  65598. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  65599. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  65600. };
  65601. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  65602. var m = transformation.m;
  65603. var m0 = SIMD.Float32x4.load(m, 0);
  65604. var m1 = SIMD.Float32x4.load(m, 4);
  65605. var m2 = SIMD.Float32x4.load(m, 8);
  65606. var m3 = SIMD.Float32x4.load(m, 12);
  65607. 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));
  65608. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  65609. result.x = SIMD.Float32x4.extractLane(r, 0);
  65610. result.y = SIMD.Float32x4.extractLane(r, 1);
  65611. result.z = SIMD.Float32x4.extractLane(r, 2);
  65612. };
  65613. return SIMDVector3;
  65614. }());
  65615. var SIMDMatrix = (function () {
  65616. function SIMDMatrix() {
  65617. }
  65618. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  65619. var tm = this.m;
  65620. var om = other.m;
  65621. var m0 = SIMD.Float32x4.load(om, 0);
  65622. var m1 = SIMD.Float32x4.load(om, 4);
  65623. var m2 = SIMD.Float32x4.load(om, 8);
  65624. var m3 = SIMD.Float32x4.load(om, 12);
  65625. for (var i = 0; i < 16; i += 4) {
  65626. 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)))));
  65627. }
  65628. return this;
  65629. };
  65630. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  65631. var src = this.m;
  65632. var dest = other.m;
  65633. // Load the 4 rows
  65634. var src0 = SIMD.Float32x4.load(src, 0);
  65635. var src1 = SIMD.Float32x4.load(src, 4);
  65636. var src2 = SIMD.Float32x4.load(src, 8);
  65637. var src3 = SIMD.Float32x4.load(src, 12);
  65638. // Transpose the source matrix. Sort of. Not a true transpose operation
  65639. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  65640. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  65641. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  65642. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  65643. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  65644. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  65645. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  65646. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  65647. // This is a true transposition, but it will lead to an incorrect result
  65648. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  65649. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  65650. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65651. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65652. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  65653. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  65654. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65655. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65656. // ----
  65657. tmp1 = SIMD.Float32x4.mul(row2, row3);
  65658. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65659. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  65660. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  65661. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65662. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  65663. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  65664. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  65665. // ----
  65666. tmp1 = SIMD.Float32x4.mul(row1, row2);
  65667. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65668. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  65669. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  65670. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65671. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  65672. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  65673. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  65674. // ----
  65675. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  65676. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65677. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  65678. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  65679. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  65680. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65681. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  65682. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  65683. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  65684. // ----
  65685. tmp1 = SIMD.Float32x4.mul(row0, row1);
  65686. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65687. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65688. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  65689. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65690. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65691. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  65692. // ----
  65693. tmp1 = SIMD.Float32x4.mul(row0, row3);
  65694. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65695. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  65696. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  65697. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65698. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  65699. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  65700. // ----
  65701. tmp1 = SIMD.Float32x4.mul(row0, row2);
  65702. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65703. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  65704. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  65705. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65706. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  65707. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  65708. // Compute determinant
  65709. var det = SIMD.Float32x4.mul(row0, minor0);
  65710. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  65711. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  65712. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  65713. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  65714. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  65715. // These shuffles aren't necessary if the faulty transposition is done
  65716. // up at the top of this function.
  65717. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  65718. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  65719. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  65720. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  65721. // Compute final values by multiplying with 1/det
  65722. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  65723. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  65724. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  65725. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  65726. return this;
  65727. };
  65728. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  65729. var out = result.m;
  65730. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  65731. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  65732. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  65733. // cc.kmVec3Subtract(f, pCenter, pEye);
  65734. var f = SIMD.Float32x4.sub(center, eye);
  65735. // cc.kmVec3Normalize(f, f);
  65736. var tmp = SIMD.Float32x4.mul(f, f);
  65737. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65738. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65739. // cc.kmVec3Assign(up, pUp);
  65740. // cc.kmVec3Normalize(up, up);
  65741. tmp = SIMD.Float32x4.mul(up, up);
  65742. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65743. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65744. // cc.kmVec3Cross(s, f, up);
  65745. 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)));
  65746. // cc.kmVec3Normalize(s, s);
  65747. tmp = SIMD.Float32x4.mul(s, s);
  65748. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65749. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65750. // cc.kmVec3Cross(u, s, f);
  65751. 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)));
  65752. // cc.kmVec3Normalize(s, s);
  65753. tmp = SIMD.Float32x4.mul(s, s);
  65754. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65755. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65756. var zero = SIMD.Float32x4.splat(0.0);
  65757. s = SIMD.Float32x4.neg(s);
  65758. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  65759. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  65760. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  65761. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  65762. 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);
  65763. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  65764. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  65765. 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)))));
  65766. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  65767. 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)))));
  65768. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  65769. 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)))));
  65770. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  65771. 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)))));
  65772. };
  65773. return SIMDMatrix;
  65774. }());
  65775. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  65776. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  65777. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  65778. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  65779. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  65780. var SIMDHelper = (function () {
  65781. function SIMDHelper() {
  65782. }
  65783. Object.defineProperty(SIMDHelper, "IsEnabled", {
  65784. get: function () {
  65785. return SIMDHelper._isEnabled;
  65786. },
  65787. enumerable: true,
  65788. configurable: true
  65789. });
  65790. SIMDHelper.DisableSIMD = function () {
  65791. // Replace functions
  65792. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  65793. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  65794. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  65795. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  65796. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  65797. SIMDHelper._isEnabled = false;
  65798. };
  65799. SIMDHelper.EnableSIMD = function () {
  65800. if (self.SIMD === undefined) {
  65801. return;
  65802. }
  65803. // check if polyfills needed
  65804. if (!self.Math.fround) {
  65805. self.Math.fround = (function (array) { return function (x) {
  65806. return array[0] = x, array[0];
  65807. }; })(new Float32Array(1));
  65808. }
  65809. if (!self.Math.imul) {
  65810. self.Math.imul = function (a, b) {
  65811. var ah = (a >>> 16) & 0xffff;
  65812. var al = a & 0xffff;
  65813. var bh = (b >>> 16) & 0xffff;
  65814. var bl = b & 0xffff;
  65815. // the shift by 0 fixes the sign on the high part
  65816. // the final |0 converts the unsigned value into a signed value
  65817. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  65818. };
  65819. }
  65820. // Replace functions
  65821. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  65822. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  65823. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  65824. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  65825. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  65826. SIMDHelper._isEnabled = true;
  65827. };
  65828. SIMDHelper._isEnabled = false;
  65829. return SIMDHelper;
  65830. }());
  65831. BABYLON.SIMDHelper = SIMDHelper;
  65832. })(BABYLON || (BABYLON = {}));
  65833. //# sourceMappingURL=babylon.math.SIMD.js.map
  65834. var BABYLON;
  65835. (function (BABYLON) {
  65836. var VRDistortionCorrectionPostProcess = (function (_super) {
  65837. __extends(VRDistortionCorrectionPostProcess, _super);
  65838. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  65839. var _this = _super.call(this, name, "vrDistortionCorrection", [
  65840. 'LensCenter',
  65841. 'Scale',
  65842. 'ScaleIn',
  65843. 'HmdWarpParam'
  65844. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  65845. _this._isRightEye = isRightEye;
  65846. _this._distortionFactors = vrMetrics.distortionK;
  65847. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  65848. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  65849. _this.adaptScaleToCurrentViewport = true;
  65850. _this.onSizeChangedObservable.add(function () {
  65851. _this.aspectRatio = _this.width * .5 / _this.height;
  65852. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  65853. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  65854. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  65855. });
  65856. _this.onApplyObservable.add(function (effect) {
  65857. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  65858. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  65859. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  65860. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  65861. });
  65862. return _this;
  65863. }
  65864. return VRDistortionCorrectionPostProcess;
  65865. }(BABYLON.PostProcess));
  65866. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  65867. })(BABYLON || (BABYLON = {}));
  65868. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  65869. var BABYLON;
  65870. (function (BABYLON) {
  65871. var AnaglyphPostProcess = (function (_super) {
  65872. __extends(AnaglyphPostProcess, _super);
  65873. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  65874. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  65875. _this._passedProcess = rigCameras[0]._rigPostProcess;
  65876. _this.onApplyObservable.add(function (effect) {
  65877. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  65878. });
  65879. return _this;
  65880. }
  65881. return AnaglyphPostProcess;
  65882. }(BABYLON.PostProcess));
  65883. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  65884. })(BABYLON || (BABYLON = {}));
  65885. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  65886. var BABYLON;
  65887. (function (BABYLON) {
  65888. var StereoscopicInterlacePostProcess = (function (_super) {
  65889. __extends(StereoscopicInterlacePostProcess, _super);
  65890. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  65891. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  65892. _this._passedProcess = rigCameras[0]._rigPostProcess;
  65893. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  65894. _this.onSizeChangedObservable.add(function () {
  65895. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  65896. });
  65897. _this.onApplyObservable.add(function (effect) {
  65898. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  65899. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  65900. });
  65901. return _this;
  65902. }
  65903. return StereoscopicInterlacePostProcess;
  65904. }(BABYLON.PostProcess));
  65905. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  65906. })(BABYLON || (BABYLON = {}));
  65907. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  65908. var BABYLON;
  65909. (function (BABYLON) {
  65910. var FreeCameraDeviceOrientationInput = (function () {
  65911. function FreeCameraDeviceOrientationInput() {
  65912. var _this = this;
  65913. this._screenOrientationAngle = 0;
  65914. this._screenQuaternion = new BABYLON.Quaternion();
  65915. this._alpha = 0;
  65916. this._beta = 0;
  65917. this._gamma = 0;
  65918. this._orientationChanged = function () {
  65919. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  65920. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  65921. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  65922. };
  65923. this._deviceOrientation = function (evt) {
  65924. _this._alpha = evt.alpha;
  65925. _this._beta = evt.beta;
  65926. _this._gamma = evt.gamma;
  65927. };
  65928. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  65929. this._orientationChanged();
  65930. }
  65931. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  65932. get: function () {
  65933. return this._camera;
  65934. },
  65935. set: function (camera) {
  65936. this._camera = camera;
  65937. if (this._camera != null && !this._camera.rotationQuaternion) {
  65938. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  65939. }
  65940. },
  65941. enumerable: true,
  65942. configurable: true
  65943. });
  65944. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65945. window.addEventListener("orientationchange", this._orientationChanged);
  65946. window.addEventListener("deviceorientation", this._deviceOrientation);
  65947. //In certain cases, the attach control is called AFTER orientation was changed,
  65948. //So this is needed.
  65949. this._orientationChanged();
  65950. };
  65951. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  65952. window.removeEventListener("orientationchange", this._orientationChanged);
  65953. window.removeEventListener("deviceorientation", this._deviceOrientation);
  65954. };
  65955. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  65956. //if no device orientation provided, don't update the rotation.
  65957. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  65958. if (!this._alpha)
  65959. return;
  65960. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  65961. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  65962. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  65963. //Mirror on XY Plane
  65964. this._camera.rotationQuaternion.z *= -1;
  65965. this._camera.rotationQuaternion.w *= -1;
  65966. };
  65967. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  65968. return "FreeCameraDeviceOrientationInput";
  65969. };
  65970. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  65971. return "deviceOrientation";
  65972. };
  65973. return FreeCameraDeviceOrientationInput;
  65974. }());
  65975. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  65976. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  65977. })(BABYLON || (BABYLON = {}));
  65978. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  65979. var BABYLON;
  65980. (function (BABYLON) {
  65981. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  65982. function ArcRotateCameraVRDeviceOrientationInput() {
  65983. this.alphaCorrection = 1;
  65984. this.betaCorrection = 1;
  65985. this.gammaCorrection = 1;
  65986. this._alpha = 0;
  65987. this._beta = 0;
  65988. this._gamma = 0;
  65989. this._dirty = false;
  65990. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  65991. }
  65992. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65993. this.camera.attachControl(element, noPreventDefault);
  65994. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  65995. };
  65996. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  65997. var camera = this.camera;
  65998. this._alpha = +evt.alpha | 0;
  65999. this._beta = +evt.beta | 0;
  66000. this._gamma = +evt.gamma | 0;
  66001. this._dirty = true;
  66002. };
  66003. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  66004. if (this._dirty) {
  66005. this._dirty = false;
  66006. if (this._gamma < 0) {
  66007. this._gamma = 180 + this._gamma;
  66008. }
  66009. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  66010. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  66011. }
  66012. };
  66013. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  66014. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  66015. };
  66016. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  66017. return "ArcRotateCameraVRDeviceOrientationInput";
  66018. };
  66019. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  66020. return "VRDeviceOrientation";
  66021. };
  66022. return ArcRotateCameraVRDeviceOrientationInput;
  66023. }());
  66024. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  66025. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  66026. })(BABYLON || (BABYLON = {}));
  66027. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  66028. var BABYLON;
  66029. (function (BABYLON) {
  66030. var VRCameraMetrics = (function () {
  66031. function VRCameraMetrics() {
  66032. this.compensateDistortion = true;
  66033. }
  66034. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  66035. get: function () {
  66036. return this.hResolution / (2 * this.vResolution);
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  66042. get: function () {
  66043. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  66044. },
  66045. enumerable: true,
  66046. configurable: true
  66047. });
  66048. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  66049. get: function () {
  66050. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66051. var h = (4 * meters) / this.hScreenSize;
  66052. return BABYLON.Matrix.Translation(h, 0, 0);
  66053. },
  66054. enumerable: true,
  66055. configurable: true
  66056. });
  66057. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  66058. get: function () {
  66059. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66060. var h = (4 * meters) / this.hScreenSize;
  66061. return BABYLON.Matrix.Translation(-h, 0, 0);
  66062. },
  66063. enumerable: true,
  66064. configurable: true
  66065. });
  66066. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  66067. get: function () {
  66068. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  66069. },
  66070. enumerable: true,
  66071. configurable: true
  66072. });
  66073. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  66074. get: function () {
  66075. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  66076. },
  66077. enumerable: true,
  66078. configurable: true
  66079. });
  66080. VRCameraMetrics.GetDefault = function () {
  66081. var result = new VRCameraMetrics();
  66082. result.hResolution = 1280;
  66083. result.vResolution = 800;
  66084. result.hScreenSize = 0.149759993;
  66085. result.vScreenSize = 0.0935999975;
  66086. result.vScreenCenter = 0.0467999987;
  66087. result.eyeToScreenDistance = 0.0410000011;
  66088. result.lensSeparationDistance = 0.0635000020;
  66089. result.interpupillaryDistance = 0.0640000030;
  66090. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  66091. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  66092. result.postProcessScaleFactor = 1.714605507808412;
  66093. result.lensCenterOffset = 0.151976421;
  66094. return result;
  66095. };
  66096. return VRCameraMetrics;
  66097. }());
  66098. BABYLON.VRCameraMetrics = VRCameraMetrics;
  66099. })(BABYLON || (BABYLON = {}));
  66100. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  66101. var BABYLON;
  66102. (function (BABYLON) {
  66103. var WebVRFreeCamera = (function (_super) {
  66104. __extends(WebVRFreeCamera, _super);
  66105. function WebVRFreeCamera(name, position, scene, webVROptions) {
  66106. if (webVROptions === void 0) { webVROptions = {}; }
  66107. var _this = _super.call(this, name, position, scene) || this;
  66108. _this.webVROptions = webVROptions;
  66109. _this._vrDevice = null;
  66110. _this.rawPose = null;
  66111. _this._vrEnabled = false;
  66112. _this._specsVersion = 1.1;
  66113. _this._attached = false;
  66114. _this._positionOffset = BABYLON.Vector3.Zero();
  66115. _this._descendants = [];
  66116. _this.devicePosition = BABYLON.Vector3.Zero();
  66117. _this.deviceScaleFactor = 1;
  66118. _this.controllers = [];
  66119. _this.onControllersAttachedObservable = new BABYLON.Observable();
  66120. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  66121. _this.minZ = 0.1;
  66122. //legacy support - the compensation boolean was removed.
  66123. if (arguments.length === 5) {
  66124. _this.webVROptions = arguments[4];
  66125. }
  66126. // default webVR options
  66127. if (_this.webVROptions.trackPosition == undefined) {
  66128. _this.webVROptions.trackPosition = true;
  66129. }
  66130. if (_this.webVROptions.controllerMeshes == undefined) {
  66131. _this.webVROptions.controllerMeshes = true;
  66132. }
  66133. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  66134. _this.webVROptions.defaultLightingOnControllers = true;
  66135. }
  66136. _this.rotationQuaternion = new BABYLON.Quaternion();
  66137. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66138. if (_this.webVROptions && _this.webVROptions.positionScale) {
  66139. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  66140. }
  66141. //enable VR
  66142. _this.getEngine().initWebVR();
  66143. //check specs version
  66144. if (!window.VRFrameData) {
  66145. _this._specsVersion = 1.0;
  66146. _this._frameData = {};
  66147. }
  66148. else {
  66149. _this._frameData = new VRFrameData();
  66150. }
  66151. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  66152. if (!device) {
  66153. return;
  66154. }
  66155. _this._vrEnabled = true;
  66156. _this._vrDevice = device;
  66157. //reset the rig parameters.
  66158. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  66159. if (_this._attached) {
  66160. _this.getEngine().enableVR(_this._vrDevice);
  66161. }
  66162. });
  66163. /**
  66164. * The idea behind the following lines:
  66165. * objects that have the camera as parent should actually have the rig cameras as a parent.
  66166. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  66167. * the second will not show it correctly.
  66168. *
  66169. * To solve this - each object that has the camera as parent will be added to a protected array.
  66170. * When the rig camera renders, it will take this array and set all of those to be its children.
  66171. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  66172. * Amazing!
  66173. */
  66174. scene.onBeforeCameraRenderObservable.add(function (camera) {
  66175. if (camera.parent === _this && _this.rigParenting) {
  66176. _this._descendants = _this.getDescendants(true, function (n) {
  66177. // don't take the cameras or the controllers!
  66178. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  66179. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  66180. return !isController && !isRigCamera;
  66181. });
  66182. _this._descendants.forEach(function (node) {
  66183. node.parent = camera;
  66184. });
  66185. }
  66186. });
  66187. scene.onAfterCameraRenderObservable.add(function (camera) {
  66188. if (camera.parent === _this && _this.rigParenting) {
  66189. _this._descendants.forEach(function (node) {
  66190. node.parent = _this;
  66191. });
  66192. }
  66193. });
  66194. return _this;
  66195. }
  66196. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  66197. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  66198. var gp = _a[_i];
  66199. if (gp.hand === name) {
  66200. return gp;
  66201. }
  66202. }
  66203. return undefined;
  66204. };
  66205. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  66206. get: function () {
  66207. if (!this._leftController) {
  66208. this._leftController = this.getControllerByName("left");
  66209. }
  66210. return this._leftController;
  66211. },
  66212. enumerable: true,
  66213. configurable: true
  66214. });
  66215. ;
  66216. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  66217. get: function () {
  66218. if (!this._rightController) {
  66219. this._rightController = this.getControllerByName("right");
  66220. }
  66221. return this._rightController;
  66222. },
  66223. enumerable: true,
  66224. configurable: true
  66225. });
  66226. ;
  66227. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  66228. if (length === void 0) { length = 100; }
  66229. if (this.leftCamera) {
  66230. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  66231. }
  66232. else {
  66233. return _super.prototype.getForwardRay.call(this, length);
  66234. }
  66235. };
  66236. WebVRFreeCamera.prototype._checkInputs = function () {
  66237. if (this._vrEnabled) {
  66238. if (this._specsVersion === 1.1) {
  66239. this._vrDevice.getFrameData(this._frameData);
  66240. }
  66241. else {
  66242. //backwards comp
  66243. var pose = this._vrDevice.getPose();
  66244. this._frameData.pose = pose;
  66245. }
  66246. this.updateFromDevice(this._frameData.pose);
  66247. }
  66248. _super.prototype._checkInputs.call(this);
  66249. };
  66250. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  66251. if (poseData && poseData.orientation) {
  66252. this.rawPose = poseData;
  66253. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  66254. if (this.getScene().useRightHandedSystem) {
  66255. this.deviceRotationQuaternion.z *= -1;
  66256. this.deviceRotationQuaternion.w *= -1;
  66257. }
  66258. if (this.webVROptions.trackPosition && this.rawPose.position) {
  66259. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  66260. if (this.getScene().useRightHandedSystem) {
  66261. this.devicePosition.z *= -1;
  66262. }
  66263. }
  66264. }
  66265. };
  66266. /**
  66267. * WebVR's attach control will start broadcasting frames to the device.
  66268. * Note that in certain browsers (chrome for example) this function must be called
  66269. * within a user-interaction callback. Example:
  66270. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  66271. *
  66272. * @param {HTMLElement} element
  66273. * @param {boolean} [noPreventDefault]
  66274. *
  66275. * @memberOf WebVRFreeCamera
  66276. */
  66277. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  66278. _super.prototype.attachControl.call(this, element, noPreventDefault);
  66279. this._attached = true;
  66280. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  66281. if (this._vrEnabled) {
  66282. this.getEngine().enableVR(this._vrDevice);
  66283. }
  66284. // try to attach the controllers, if found.
  66285. this.initControllers();
  66286. };
  66287. WebVRFreeCamera.prototype.detachControl = function (element) {
  66288. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66289. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66290. _super.prototype.detachControl.call(this, element);
  66291. this._vrEnabled = false;
  66292. this._attached = false;
  66293. this.getEngine().disableVR();
  66294. };
  66295. WebVRFreeCamera.prototype.getClassName = function () {
  66296. return "WebVRFreeCamera";
  66297. };
  66298. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  66299. //uses the vrDisplay's "resetPose()".
  66300. //pitch and roll won't be affected.
  66301. this._vrDevice.resetPose();
  66302. };
  66303. WebVRFreeCamera.prototype._updateRigCameras = function () {
  66304. var camLeft = this._rigCameras[0];
  66305. var camRight = this._rigCameras[1];
  66306. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66307. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66308. camLeft.position.copyFrom(this.devicePosition);
  66309. camRight.position.copyFrom(this.devicePosition);
  66310. };
  66311. /**
  66312. * This function is called by the two RIG cameras.
  66313. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  66314. */
  66315. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  66316. var _this = this;
  66317. //WebVR 1.0
  66318. if (this._cameraRigParams["specs"] === 1.0) {
  66319. this._updateCameraRotationMatrix();
  66320. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66321. // Computing target and final matrix
  66322. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66323. if (this.getScene().useRightHandedSystem) {
  66324. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66325. }
  66326. else {
  66327. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66328. }
  66329. //now move the eye in the right direction
  66330. var eyeParams = this._cameraRigParams["eyeParameters"];
  66331. var offset = eyeParams.offset;
  66332. // it will actually always be 0, but just in case
  66333. if (this.getScene().useRightHandedSystem) {
  66334. offset[2] *= -1;
  66335. }
  66336. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  66337. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  66338. }
  66339. else {
  66340. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  66341. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  66342. if (!this.getScene().useRightHandedSystem) {
  66343. [2, 6, 8, 9, 14].forEach(function (num) {
  66344. _this._webvrViewMatrix.m[num] *= -1;
  66345. });
  66346. }
  66347. // update the camera rotation matrix
  66348. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  66349. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66350. // Computing target and final matrix
  66351. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66352. }
  66353. var parentCamera = this._cameraRigParams["parentCamera"];
  66354. // should the view matrix be updated with scale and position offset?
  66355. if (parentCamera.deviceScaleFactor !== 1) {
  66356. this._webvrViewMatrix.invert();
  66357. // scale the position, if set
  66358. if (parentCamera.deviceScaleFactor) {
  66359. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  66360. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  66361. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  66362. }
  66363. this._webvrViewMatrix.invert();
  66364. }
  66365. return this._webvrViewMatrix;
  66366. };
  66367. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  66368. var _this = this;
  66369. if (this._cameraRigParams["specs"] === 1.0) {
  66370. var eyeParams = this._cameraRigParams["eyeParameters"];
  66371. // deprecated!!
  66372. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  66373. }
  66374. else {
  66375. var parentCamera = this.parent;
  66376. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  66377. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  66378. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  66379. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  66380. //babylon compatible matrix
  66381. if (!this.getScene().useRightHandedSystem) {
  66382. [8, 9, 10, 11].forEach(function (num) {
  66383. _this._projectionMatrix.m[num] *= -1;
  66384. });
  66385. }
  66386. }
  66387. return this._projectionMatrix;
  66388. };
  66389. WebVRFreeCamera.prototype.initControllers = function () {
  66390. var _this = this;
  66391. this.controllers = [];
  66392. var manager = this.getScene().gamepadManager;
  66393. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66394. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66395. var webVrController = gamepad;
  66396. if (webVrController.defaultModel) {
  66397. webVrController.defaultModel.setEnabled(false);
  66398. }
  66399. }
  66400. });
  66401. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66402. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66403. var webVrController = gamepad;
  66404. if (_this.webVROptions.controllerMeshes) {
  66405. if (webVrController.defaultModel) {
  66406. webVrController.defaultModel.setEnabled(true);
  66407. }
  66408. else {
  66409. // Load the meshes
  66410. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  66411. if (_this.webVROptions.defaultLightingOnControllers) {
  66412. if (!_this._lightOnControllers) {
  66413. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  66414. }
  66415. var activateLightOnSubMeshes_1 = function (mesh, light) {
  66416. var children = mesh.getChildren();
  66417. if (children.length !== 0) {
  66418. children.forEach(function (mesh) {
  66419. light.includedOnlyMeshes.push(mesh);
  66420. activateLightOnSubMeshes_1(mesh, light);
  66421. });
  66422. }
  66423. };
  66424. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  66425. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  66426. }
  66427. });
  66428. }
  66429. }
  66430. webVrController.attachToPoseControlledCamera(_this);
  66431. // since this is async - sanity check. Is the controller already stored?
  66432. if (_this.controllers.indexOf(webVrController) === -1) {
  66433. //add to the controllers array
  66434. _this.controllers.push(webVrController);
  66435. //did we find enough controllers? Great! let the developer know.
  66436. if (_this.controllers.length >= 2) {
  66437. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  66438. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  66439. // So we're overriding setting left & right manually to be sure
  66440. var firstViveWandDetected = false;
  66441. for (var i = 0; i < _this.controllers.length; i++) {
  66442. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  66443. if (!firstViveWandDetected) {
  66444. firstViveWandDetected = true;
  66445. _this.controllers[i].hand = "left";
  66446. }
  66447. else {
  66448. _this.controllers[i].hand = "right";
  66449. }
  66450. }
  66451. }
  66452. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  66453. }
  66454. }
  66455. }
  66456. });
  66457. };
  66458. return WebVRFreeCamera;
  66459. }(BABYLON.FreeCamera));
  66460. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  66461. })(BABYLON || (BABYLON = {}));
  66462. //# sourceMappingURL=babylon.webVRCamera.js.map
  66463. /// <reference path="babylon.freeCamera.ts" />
  66464. var BABYLON;
  66465. (function (BABYLON) {
  66466. // We're mainly based on the logic defined into the FreeCamera code
  66467. var DeviceOrientationCamera = (function (_super) {
  66468. __extends(DeviceOrientationCamera, _super);
  66469. function DeviceOrientationCamera(name, position, scene) {
  66470. var _this = _super.call(this, name, position, scene) || this;
  66471. _this._quaternionCache = new BABYLON.Quaternion();
  66472. _this.inputs.addDeviceOrientation();
  66473. return _this;
  66474. }
  66475. DeviceOrientationCamera.prototype.getClassName = function () {
  66476. return "DeviceOrientationCamera";
  66477. };
  66478. DeviceOrientationCamera.prototype._checkInputs = function () {
  66479. _super.prototype._checkInputs.call(this);
  66480. this._quaternionCache.copyFrom(this.rotationQuaternion);
  66481. if (this._initialQuaternion) {
  66482. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66483. }
  66484. };
  66485. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  66486. var _this = this;
  66487. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  66488. //can only work if this camera has a rotation quaternion already.
  66489. if (!this.rotationQuaternion)
  66490. return;
  66491. if (!this._initialQuaternion) {
  66492. this._initialQuaternion = new BABYLON.Quaternion();
  66493. }
  66494. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  66495. ['x', 'y', 'z'].forEach(function (axisName) {
  66496. if (!axis[axisName]) {
  66497. _this._initialQuaternion[axisName] = 0;
  66498. }
  66499. else {
  66500. _this._initialQuaternion[axisName] *= -1;
  66501. }
  66502. });
  66503. this._initialQuaternion.normalize();
  66504. //force rotation update
  66505. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66506. };
  66507. return DeviceOrientationCamera;
  66508. }(BABYLON.FreeCamera));
  66509. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  66510. })(BABYLON || (BABYLON = {}));
  66511. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  66512. var BABYLON;
  66513. (function (BABYLON) {
  66514. var VRDeviceOrientationFreeCamera = (function (_super) {
  66515. __extends(VRDeviceOrientationFreeCamera, _super);
  66516. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66517. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66518. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66519. var _this = _super.call(this, name, position, scene) || this;
  66520. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66521. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66522. return _this;
  66523. }
  66524. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  66525. return "VRDeviceOrientationFreeCamera";
  66526. };
  66527. return VRDeviceOrientationFreeCamera;
  66528. }(BABYLON.DeviceOrientationCamera));
  66529. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  66530. var VRDeviceOrientationGamepadCamera = (function (_super) {
  66531. __extends(VRDeviceOrientationGamepadCamera, _super);
  66532. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66533. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66534. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66535. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  66536. _this.inputs.addGamepad();
  66537. return _this;
  66538. }
  66539. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  66540. return "VRDeviceOrientationGamepadCamera";
  66541. };
  66542. return VRDeviceOrientationGamepadCamera;
  66543. }(VRDeviceOrientationFreeCamera));
  66544. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  66545. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  66546. __extends(VRDeviceOrientationArcRotateCamera, _super);
  66547. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  66548. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66549. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66550. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66551. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66552. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66553. _this.inputs.addVRDeviceOrientation();
  66554. return _this;
  66555. }
  66556. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  66557. return "VRDeviceOrientationArcRotateCamera";
  66558. };
  66559. return VRDeviceOrientationArcRotateCamera;
  66560. }(BABYLON.ArcRotateCamera));
  66561. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  66562. })(BABYLON || (BABYLON = {}));
  66563. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  66564. /// <reference path="babylon.freeCamera.ts" />
  66565. /// <reference path="babylon.arcRotateCamera.ts" />
  66566. /// <reference path="babylon.gamepadCamera.ts" />
  66567. /// <reference path="babylon.universalCamera.ts" />
  66568. var BABYLON;
  66569. (function (BABYLON) {
  66570. var AnaglyphFreeCamera = (function (_super) {
  66571. __extends(AnaglyphFreeCamera, _super);
  66572. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  66573. var _this = _super.call(this, name, position, scene) || this;
  66574. _this.interaxialDistance = interaxialDistance;
  66575. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66576. return _this;
  66577. }
  66578. AnaglyphFreeCamera.prototype.getClassName = function () {
  66579. return "AnaglyphFreeCamera";
  66580. };
  66581. return AnaglyphFreeCamera;
  66582. }(BABYLON.FreeCamera));
  66583. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  66584. var AnaglyphArcRotateCamera = (function (_super) {
  66585. __extends(AnaglyphArcRotateCamera, _super);
  66586. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  66587. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66588. _this.interaxialDistance = interaxialDistance;
  66589. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66590. return _this;
  66591. }
  66592. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  66593. return "AnaglyphArcRotateCamera";
  66594. };
  66595. return AnaglyphArcRotateCamera;
  66596. }(BABYLON.ArcRotateCamera));
  66597. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  66598. var AnaglyphGamepadCamera = (function (_super) {
  66599. __extends(AnaglyphGamepadCamera, _super);
  66600. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  66601. var _this = _super.call(this, name, position, scene) || this;
  66602. _this.interaxialDistance = interaxialDistance;
  66603. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66604. return _this;
  66605. }
  66606. AnaglyphGamepadCamera.prototype.getClassName = function () {
  66607. return "AnaglyphGamepadCamera";
  66608. };
  66609. return AnaglyphGamepadCamera;
  66610. }(BABYLON.GamepadCamera));
  66611. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  66612. var AnaglyphUniversalCamera = (function (_super) {
  66613. __extends(AnaglyphUniversalCamera, _super);
  66614. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  66615. var _this = _super.call(this, name, position, scene) || this;
  66616. _this.interaxialDistance = interaxialDistance;
  66617. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66618. return _this;
  66619. }
  66620. AnaglyphUniversalCamera.prototype.getClassName = function () {
  66621. return "AnaglyphUniversalCamera";
  66622. };
  66623. return AnaglyphUniversalCamera;
  66624. }(BABYLON.UniversalCamera));
  66625. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  66626. var StereoscopicFreeCamera = (function (_super) {
  66627. __extends(StereoscopicFreeCamera, _super);
  66628. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66629. var _this = _super.call(this, name, position, scene) || this;
  66630. _this.interaxialDistance = interaxialDistance;
  66631. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66632. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66633. return _this;
  66634. }
  66635. StereoscopicFreeCamera.prototype.getClassName = function () {
  66636. return "StereoscopicFreeCamera";
  66637. };
  66638. return StereoscopicFreeCamera;
  66639. }(BABYLON.FreeCamera));
  66640. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  66641. var StereoscopicArcRotateCamera = (function (_super) {
  66642. __extends(StereoscopicArcRotateCamera, _super);
  66643. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  66644. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66645. _this.interaxialDistance = interaxialDistance;
  66646. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66647. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66648. return _this;
  66649. }
  66650. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  66651. return "StereoscopicArcRotateCamera";
  66652. };
  66653. return StereoscopicArcRotateCamera;
  66654. }(BABYLON.ArcRotateCamera));
  66655. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  66656. var StereoscopicGamepadCamera = (function (_super) {
  66657. __extends(StereoscopicGamepadCamera, _super);
  66658. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66659. var _this = _super.call(this, name, position, scene) || this;
  66660. _this.interaxialDistance = interaxialDistance;
  66661. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66662. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66663. return _this;
  66664. }
  66665. StereoscopicGamepadCamera.prototype.getClassName = function () {
  66666. return "StereoscopicGamepadCamera";
  66667. };
  66668. return StereoscopicGamepadCamera;
  66669. }(BABYLON.GamepadCamera));
  66670. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  66671. var StereoscopicUniversalCamera = (function (_super) {
  66672. __extends(StereoscopicUniversalCamera, _super);
  66673. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66674. var _this = _super.call(this, name, position, scene) || this;
  66675. _this.interaxialDistance = interaxialDistance;
  66676. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66677. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66678. return _this;
  66679. }
  66680. StereoscopicUniversalCamera.prototype.getClassName = function () {
  66681. return "StereoscopicUniversalCamera";
  66682. };
  66683. return StereoscopicUniversalCamera;
  66684. }(BABYLON.UniversalCamera));
  66685. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  66686. })(BABYLON || (BABYLON = {}));
  66687. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  66688. var BABYLON;
  66689. (function (BABYLON) {
  66690. var VRExperienceHelper = (function () {
  66691. function VRExperienceHelper(scene, webVROptions) {
  66692. if (webVROptions === void 0) { webVROptions = {}; }
  66693. var _this = this;
  66694. this.webVROptions = webVROptions;
  66695. this._webVRsupportedAndReady = false;
  66696. this._isInVRMode = false;
  66697. this._scene = scene;
  66698. if (!this._scene.activeCamera) {
  66699. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  66700. }
  66701. else {
  66702. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  66703. if (scene.activeCamera.rotation) {
  66704. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  66705. }
  66706. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  66707. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  66708. }
  66709. this._scene.activeCamera = this._deviceOrientationCamera;
  66710. this._position = this._scene.activeCamera.position;
  66711. this._canvas = scene.getEngine().getRenderingCanvas();
  66712. this._scene.activeCamera.attachControl(this._canvas);
  66713. this._btnVR = document.createElement("BUTTON");
  66714. this._btnVR.className = "babylonVRicon";
  66715. this._btnVR.id = "babylonVRiconbtn";
  66716. this._btnVR.title = "Click to switch to VR";
  66717. 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) }";
  66718. var style = document.createElement('style');
  66719. style.appendChild(document.createTextNode(css));
  66720. document.getElementsByTagName('head')[0].appendChild(style);
  66721. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  66722. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  66723. window.addEventListener("resize", function () {
  66724. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  66725. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  66726. });
  66727. // Exiting VR mode using 'ESC' key on desktop
  66728. document.addEventListener("keydown", function (event) {
  66729. if (event.keyCode === 27 && _this._isInVRMode) {
  66730. _this.exitVR();
  66731. }
  66732. });
  66733. // Exiting VR mode double tapping the touch screen
  66734. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  66735. if (_this._isInVRMode) {
  66736. _this.exitVR();
  66737. }
  66738. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  66739. if (navigator.getVRDisplays) {
  66740. navigator.getVRDisplays().then(function (headsets) {
  66741. if (headsets.length > 0) {
  66742. _this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", _this._position, _this._scene);
  66743. _this._webVRsupportedAndReady = true;
  66744. }
  66745. document.body.appendChild(_this._btnVR);
  66746. });
  66747. }
  66748. else {
  66749. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  66750. document.body.appendChild(this._btnVR);
  66751. }
  66752. this._btnVR.addEventListener("click", function () {
  66753. _this.enterVR();
  66754. });
  66755. }
  66756. VRExperienceHelper.prototype.enterVR = function () {
  66757. // If WebVR is supported and a headset is connected
  66758. if (this._webVRsupportedAndReady) {
  66759. this._webVRCamera.position = this._position;
  66760. this._scene.activeCamera = this._webVRCamera;
  66761. }
  66762. else {
  66763. this._vrDeviceOrientationCamera.position = this._position;
  66764. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  66765. this._scene.getEngine().switchFullscreen(true);
  66766. }
  66767. this._scene.activeCamera.attachControl(this._canvas);
  66768. this._isInVRMode = true;
  66769. this._btnVR.style.display = "none";
  66770. };
  66771. VRExperienceHelper.prototype.exitVR = function () {
  66772. if (this._webVRsupportedAndReady) {
  66773. this._scene.getEngine().disableVR();
  66774. }
  66775. if (this._scene.activeCamera) {
  66776. this._position = this._scene.activeCamera.position;
  66777. }
  66778. this._deviceOrientationCamera.position = this._position;
  66779. this._scene.activeCamera = this._deviceOrientationCamera;
  66780. this._scene.activeCamera.attachControl(this._canvas);
  66781. this._isInVRMode = false;
  66782. this._btnVR.style.display = "";
  66783. };
  66784. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  66785. get: function () {
  66786. return this._position;
  66787. },
  66788. set: function (value) {
  66789. this._position = value;
  66790. this._scene.activeCamera.position = value;
  66791. },
  66792. enumerable: true,
  66793. configurable: true
  66794. });
  66795. VRExperienceHelper.prototype.dispose = function () {
  66796. if (this._isInVRMode) {
  66797. this.exitVR();
  66798. }
  66799. this._deviceOrientationCamera.dispose();
  66800. if (this._webVRCamera) {
  66801. this._webVRCamera.dispose();
  66802. }
  66803. if (this._vrDeviceOrientationCamera) {
  66804. this._vrDeviceOrientationCamera.dispose();
  66805. }
  66806. document.body.removeChild(this._btnVR);
  66807. };
  66808. VRExperienceHelper.prototype.getClassName = function () {
  66809. return "VRExperienceHelper";
  66810. };
  66811. return VRExperienceHelper;
  66812. }());
  66813. BABYLON.VRExperienceHelper = VRExperienceHelper;
  66814. })(BABYLON || (BABYLON = {}));
  66815. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  66816. // Mainly based on these 2 articles :
  66817. // 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
  66818. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  66819. var BABYLON;
  66820. (function (BABYLON) {
  66821. var JoystickAxis;
  66822. (function (JoystickAxis) {
  66823. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  66824. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  66825. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  66826. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  66827. var VirtualJoystick = (function () {
  66828. function VirtualJoystick(leftJoystick) {
  66829. var _this = this;
  66830. if (leftJoystick) {
  66831. this._leftJoystick = true;
  66832. }
  66833. else {
  66834. this._leftJoystick = false;
  66835. }
  66836. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  66837. VirtualJoystick._globalJoystickIndex++;
  66838. // By default left & right arrow keys are moving the X
  66839. // and up & down keys are moving the Y
  66840. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  66841. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  66842. this.reverseLeftRight = false;
  66843. this.reverseUpDown = false;
  66844. // collections of pointers
  66845. this._touches = new BABYLON.StringDictionary();
  66846. this.deltaPosition = BABYLON.Vector3.Zero();
  66847. this._joystickSensibility = 25;
  66848. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  66849. this._rotationSpeed = 25;
  66850. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  66851. this._rotateOnAxisRelativeToMesh = false;
  66852. this._onResize = function (evt) {
  66853. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  66854. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  66855. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  66856. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  66857. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  66858. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  66859. };
  66860. // injecting a canvas element on top of the canvas 3D game
  66861. if (!VirtualJoystick.vjCanvas) {
  66862. window.addEventListener("resize", this._onResize, false);
  66863. VirtualJoystick.vjCanvas = document.createElement("canvas");
  66864. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  66865. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  66866. VirtualJoystick.vjCanvas.width = window.innerWidth;
  66867. VirtualJoystick.vjCanvas.height = window.innerHeight;
  66868. VirtualJoystick.vjCanvas.style.width = "100%";
  66869. VirtualJoystick.vjCanvas.style.height = "100%";
  66870. VirtualJoystick.vjCanvas.style.position = "absolute";
  66871. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  66872. VirtualJoystick.vjCanvas.style.top = "0px";
  66873. VirtualJoystick.vjCanvas.style.left = "0px";
  66874. VirtualJoystick.vjCanvas.style.zIndex = "5";
  66875. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  66876. // Support for jQuery PEP polyfill
  66877. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  66878. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  66879. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  66880. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  66881. document.body.appendChild(VirtualJoystick.vjCanvas);
  66882. }
  66883. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  66884. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  66885. this.pressed = false;
  66886. // default joystick color
  66887. this._joystickColor = "cyan";
  66888. this._joystickPointerID = -1;
  66889. // current joystick position
  66890. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  66891. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  66892. // origin joystick position
  66893. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  66894. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  66895. this._onPointerDownHandlerRef = function (evt) {
  66896. _this._onPointerDown(evt);
  66897. };
  66898. this._onPointerMoveHandlerRef = function (evt) {
  66899. _this._onPointerMove(evt);
  66900. };
  66901. this._onPointerOutHandlerRef = function (evt) {
  66902. _this._onPointerUp(evt);
  66903. };
  66904. this._onPointerUpHandlerRef = function (evt) {
  66905. _this._onPointerUp(evt);
  66906. };
  66907. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  66908. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  66909. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  66910. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  66911. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  66912. evt.preventDefault(); // Disables system menu
  66913. }, false);
  66914. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  66915. }
  66916. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  66917. this._joystickSensibility = newJoystickSensibility;
  66918. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  66919. };
  66920. VirtualJoystick.prototype._onPointerDown = function (e) {
  66921. var positionOnScreenCondition;
  66922. e.preventDefault();
  66923. if (this._leftJoystick === true) {
  66924. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  66925. }
  66926. else {
  66927. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  66928. }
  66929. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  66930. // First contact will be dedicated to the virtual joystick
  66931. this._joystickPointerID = e.pointerId;
  66932. this._joystickPointerStartPos.x = e.clientX;
  66933. this._joystickPointerStartPos.y = e.clientY;
  66934. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  66935. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  66936. this._deltaJoystickVector.x = 0;
  66937. this._deltaJoystickVector.y = 0;
  66938. this.pressed = true;
  66939. this._touches.add(e.pointerId.toString(), e);
  66940. }
  66941. else {
  66942. // You can only trigger the action buttons with a joystick declared
  66943. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  66944. this._action();
  66945. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  66946. }
  66947. }
  66948. };
  66949. VirtualJoystick.prototype._onPointerMove = function (e) {
  66950. // If the current pointer is the one associated to the joystick (first touch contact)
  66951. if (this._joystickPointerID == e.pointerId) {
  66952. this._joystickPointerPos.x = e.clientX;
  66953. this._joystickPointerPos.y = e.clientY;
  66954. this._deltaJoystickVector = this._joystickPointerPos.clone();
  66955. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  66956. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  66957. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  66958. switch (this._axisTargetedByLeftAndRight) {
  66959. case JoystickAxis.X:
  66960. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  66961. break;
  66962. case JoystickAxis.Y:
  66963. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  66964. break;
  66965. case JoystickAxis.Z:
  66966. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  66967. break;
  66968. }
  66969. var directionUpDown = this.reverseUpDown ? 1 : -1;
  66970. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  66971. switch (this._axisTargetedByUpAndDown) {
  66972. case JoystickAxis.X:
  66973. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  66974. break;
  66975. case JoystickAxis.Y:
  66976. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  66977. break;
  66978. case JoystickAxis.Z:
  66979. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  66980. break;
  66981. }
  66982. }
  66983. else {
  66984. var data = this._touches.get(e.pointerId.toString());
  66985. if (data) {
  66986. data.x = e.clientX;
  66987. data.y = e.clientY;
  66988. }
  66989. }
  66990. };
  66991. VirtualJoystick.prototype._onPointerUp = function (e) {
  66992. if (this._joystickPointerID == e.pointerId) {
  66993. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  66994. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  66995. this._joystickPointerID = -1;
  66996. this.pressed = false;
  66997. }
  66998. else {
  66999. var touch = this._touches.get(e.pointerId.toString());
  67000. if (touch) {
  67001. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67002. }
  67003. }
  67004. this._deltaJoystickVector.x = 0;
  67005. this._deltaJoystickVector.y = 0;
  67006. this._touches.remove(e.pointerId.toString());
  67007. };
  67008. /**
  67009. * Change the color of the virtual joystick
  67010. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  67011. */
  67012. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  67013. this._joystickColor = newColor;
  67014. };
  67015. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  67016. this._action = action;
  67017. };
  67018. // Define which axis you'd like to control for left & right
  67019. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  67020. switch (axis) {
  67021. case JoystickAxis.X:
  67022. case JoystickAxis.Y:
  67023. case JoystickAxis.Z:
  67024. this._axisTargetedByLeftAndRight = axis;
  67025. break;
  67026. default:
  67027. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67028. break;
  67029. }
  67030. };
  67031. // Define which axis you'd like to control for up & down
  67032. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  67033. switch (axis) {
  67034. case JoystickAxis.X:
  67035. case JoystickAxis.Y:
  67036. case JoystickAxis.Z:
  67037. this._axisTargetedByUpAndDown = axis;
  67038. break;
  67039. default:
  67040. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67041. break;
  67042. }
  67043. };
  67044. VirtualJoystick.prototype._clearCanvas = function () {
  67045. if (this._leftJoystick) {
  67046. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  67047. }
  67048. else {
  67049. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  67050. }
  67051. };
  67052. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  67053. var _this = this;
  67054. if (this.pressed) {
  67055. this._touches.forEach(function (key, touch) {
  67056. if (touch.pointerId === _this._joystickPointerID) {
  67057. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  67058. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  67059. VirtualJoystick.vjCanvasContext.beginPath();
  67060. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67061. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67062. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  67063. VirtualJoystick.vjCanvasContext.stroke();
  67064. VirtualJoystick.vjCanvasContext.closePath();
  67065. VirtualJoystick.vjCanvasContext.beginPath();
  67066. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67067. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67068. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  67069. VirtualJoystick.vjCanvasContext.stroke();
  67070. VirtualJoystick.vjCanvasContext.closePath();
  67071. VirtualJoystick.vjCanvasContext.beginPath();
  67072. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67073. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  67074. VirtualJoystick.vjCanvasContext.stroke();
  67075. VirtualJoystick.vjCanvasContext.closePath();
  67076. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  67077. }
  67078. else {
  67079. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67080. VirtualJoystick.vjCanvasContext.beginPath();
  67081. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  67082. VirtualJoystick.vjCanvasContext.beginPath();
  67083. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  67084. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67085. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  67086. VirtualJoystick.vjCanvasContext.stroke();
  67087. VirtualJoystick.vjCanvasContext.closePath();
  67088. touch.prevX = touch.x;
  67089. touch.prevY = touch.y;
  67090. }
  67091. ;
  67092. });
  67093. }
  67094. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67095. };
  67096. VirtualJoystick.prototype.releaseCanvas = function () {
  67097. if (VirtualJoystick.vjCanvas) {
  67098. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  67099. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  67100. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  67101. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  67102. window.removeEventListener("resize", this._onResize);
  67103. document.body.removeChild(VirtualJoystick.vjCanvas);
  67104. VirtualJoystick.vjCanvas = null;
  67105. }
  67106. };
  67107. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  67108. VirtualJoystick._globalJoystickIndex = 0;
  67109. return VirtualJoystick;
  67110. }());
  67111. BABYLON.VirtualJoystick = VirtualJoystick;
  67112. })(BABYLON || (BABYLON = {}));
  67113. //# sourceMappingURL=babylon.virtualJoystick.js.map
  67114. var BABYLON;
  67115. (function (BABYLON) {
  67116. // We're mainly based on the logic defined into the FreeCamera code
  67117. var VirtualJoysticksCamera = (function (_super) {
  67118. __extends(VirtualJoysticksCamera, _super);
  67119. function VirtualJoysticksCamera(name, position, scene) {
  67120. var _this = _super.call(this, name, position, scene) || this;
  67121. _this.inputs.addVirtualJoystick();
  67122. return _this;
  67123. }
  67124. VirtualJoysticksCamera.prototype.getClassName = function () {
  67125. return "VirtualJoysticksCamera";
  67126. };
  67127. return VirtualJoysticksCamera;
  67128. }(BABYLON.FreeCamera));
  67129. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  67130. })(BABYLON || (BABYLON = {}));
  67131. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  67132. var BABYLON;
  67133. (function (BABYLON) {
  67134. var FreeCameraVirtualJoystickInput = (function () {
  67135. function FreeCameraVirtualJoystickInput() {
  67136. }
  67137. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  67138. return this._leftjoystick;
  67139. };
  67140. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  67141. return this._rightjoystick;
  67142. };
  67143. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  67144. if (this._leftjoystick) {
  67145. var camera = this.camera;
  67146. var speed = camera._computeLocalCameraSpeed() * 50;
  67147. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  67148. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  67149. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  67150. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  67151. if (!this._leftjoystick.pressed) {
  67152. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  67153. }
  67154. if (!this._rightjoystick.pressed) {
  67155. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  67156. }
  67157. }
  67158. };
  67159. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  67160. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  67161. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  67162. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  67163. this._leftjoystick.setJoystickSensibility(0.15);
  67164. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  67165. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  67166. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  67167. this._rightjoystick.reverseUpDown = true;
  67168. this._rightjoystick.setJoystickSensibility(0.05);
  67169. this._rightjoystick.setJoystickColor("yellow");
  67170. };
  67171. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  67172. this._leftjoystick.releaseCanvas();
  67173. this._rightjoystick.releaseCanvas();
  67174. };
  67175. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  67176. return "FreeCameraVirtualJoystickInput";
  67177. };
  67178. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  67179. return "virtualJoystick";
  67180. };
  67181. return FreeCameraVirtualJoystickInput;
  67182. }());
  67183. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  67184. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  67185. })(BABYLON || (BABYLON = {}));
  67186. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  67187. var BABYLON;
  67188. (function (BABYLON) {
  67189. var SimplificationSettings = (function () {
  67190. function SimplificationSettings(quality, distance, optimizeMesh) {
  67191. this.quality = quality;
  67192. this.distance = distance;
  67193. this.optimizeMesh = optimizeMesh;
  67194. }
  67195. return SimplificationSettings;
  67196. }());
  67197. BABYLON.SimplificationSettings = SimplificationSettings;
  67198. var SimplificationQueue = (function () {
  67199. function SimplificationQueue() {
  67200. this.running = false;
  67201. this._simplificationArray = [];
  67202. }
  67203. SimplificationQueue.prototype.addTask = function (task) {
  67204. this._simplificationArray.push(task);
  67205. };
  67206. SimplificationQueue.prototype.executeNext = function () {
  67207. var task = this._simplificationArray.pop();
  67208. if (task) {
  67209. this.running = true;
  67210. this.runSimplification(task);
  67211. }
  67212. else {
  67213. this.running = false;
  67214. }
  67215. };
  67216. SimplificationQueue.prototype.runSimplification = function (task) {
  67217. var _this = this;
  67218. if (task.parallelProcessing) {
  67219. //parallel simplifier
  67220. task.settings.forEach(function (setting) {
  67221. var simplifier = _this.getSimplifier(task);
  67222. simplifier.simplify(setting, function (newMesh) {
  67223. task.mesh.addLODLevel(setting.distance, newMesh);
  67224. newMesh.isVisible = true;
  67225. //check if it is the last
  67226. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  67227. //all done, run the success callback.
  67228. task.successCallback();
  67229. }
  67230. _this.executeNext();
  67231. });
  67232. });
  67233. }
  67234. else {
  67235. //single simplifier.
  67236. var simplifier = this.getSimplifier(task);
  67237. var runDecimation = function (setting, callback) {
  67238. simplifier.simplify(setting, function (newMesh) {
  67239. task.mesh.addLODLevel(setting.distance, newMesh);
  67240. newMesh.isVisible = true;
  67241. //run the next quality level
  67242. callback();
  67243. });
  67244. };
  67245. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  67246. runDecimation(task.settings[loop.index], function () {
  67247. loop.executeNext();
  67248. });
  67249. }, function () {
  67250. //execution ended, run the success callback.
  67251. if (task.successCallback) {
  67252. task.successCallback();
  67253. }
  67254. _this.executeNext();
  67255. });
  67256. }
  67257. };
  67258. SimplificationQueue.prototype.getSimplifier = function (task) {
  67259. switch (task.simplificationType) {
  67260. case SimplificationType.QUADRATIC:
  67261. default:
  67262. return new QuadraticErrorSimplification(task.mesh);
  67263. }
  67264. };
  67265. return SimplificationQueue;
  67266. }());
  67267. BABYLON.SimplificationQueue = SimplificationQueue;
  67268. /**
  67269. * The implemented types of simplification.
  67270. * At the moment only Quadratic Error Decimation is implemented.
  67271. */
  67272. var SimplificationType;
  67273. (function (SimplificationType) {
  67274. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  67275. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  67276. var DecimationTriangle = (function () {
  67277. function DecimationTriangle(vertices) {
  67278. this.vertices = vertices;
  67279. this.error = new Array(4);
  67280. this.deleted = false;
  67281. this.isDirty = false;
  67282. this.deletePending = false;
  67283. this.borderFactor = 0;
  67284. }
  67285. return DecimationTriangle;
  67286. }());
  67287. BABYLON.DecimationTriangle = DecimationTriangle;
  67288. var DecimationVertex = (function () {
  67289. function DecimationVertex(position, id) {
  67290. this.position = position;
  67291. this.id = id;
  67292. this.isBorder = true;
  67293. this.q = new QuadraticMatrix();
  67294. this.triangleCount = 0;
  67295. this.triangleStart = 0;
  67296. this.originalOffsets = [];
  67297. }
  67298. DecimationVertex.prototype.updatePosition = function (newPosition) {
  67299. this.position.copyFrom(newPosition);
  67300. };
  67301. return DecimationVertex;
  67302. }());
  67303. BABYLON.DecimationVertex = DecimationVertex;
  67304. var QuadraticMatrix = (function () {
  67305. function QuadraticMatrix(data) {
  67306. this.data = new Array(10);
  67307. for (var i = 0; i < 10; ++i) {
  67308. if (data && data[i]) {
  67309. this.data[i] = data[i];
  67310. }
  67311. else {
  67312. this.data[i] = 0;
  67313. }
  67314. }
  67315. }
  67316. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  67317. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  67318. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  67319. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  67320. return det;
  67321. };
  67322. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  67323. for (var i = 0; i < 10; ++i) {
  67324. this.data[i] += matrix.data[i];
  67325. }
  67326. };
  67327. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  67328. for (var i = 0; i < 10; ++i) {
  67329. this.data[i] += data[i];
  67330. }
  67331. };
  67332. QuadraticMatrix.prototype.add = function (matrix) {
  67333. var m = new QuadraticMatrix();
  67334. for (var i = 0; i < 10; ++i) {
  67335. m.data[i] = this.data[i] + matrix.data[i];
  67336. }
  67337. return m;
  67338. };
  67339. QuadraticMatrix.FromData = function (a, b, c, d) {
  67340. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  67341. };
  67342. //returning an array to avoid garbage collection
  67343. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  67344. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  67345. };
  67346. return QuadraticMatrix;
  67347. }());
  67348. BABYLON.QuadraticMatrix = QuadraticMatrix;
  67349. var Reference = (function () {
  67350. function Reference(vertexId, triangleId) {
  67351. this.vertexId = vertexId;
  67352. this.triangleId = triangleId;
  67353. }
  67354. return Reference;
  67355. }());
  67356. BABYLON.Reference = Reference;
  67357. /**
  67358. * An implementation of the Quadratic Error simplification algorithm.
  67359. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  67360. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  67361. * @author RaananW
  67362. */
  67363. var QuadraticErrorSimplification = (function () {
  67364. function QuadraticErrorSimplification(_mesh) {
  67365. this._mesh = _mesh;
  67366. this.initialized = false;
  67367. this.syncIterations = 5000;
  67368. this.aggressiveness = 7;
  67369. this.decimationIterations = 100;
  67370. this.boundingBoxEpsilon = BABYLON.Epsilon;
  67371. }
  67372. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  67373. var _this = this;
  67374. this.initDecimatedMesh();
  67375. //iterating through the submeshes array, one after the other.
  67376. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  67377. _this.initWithMesh(loop.index, function () {
  67378. _this.runDecimation(settings, loop.index, function () {
  67379. loop.executeNext();
  67380. });
  67381. }, settings.optimizeMesh);
  67382. }, function () {
  67383. setTimeout(function () {
  67384. successCallback(_this._reconstructedMesh);
  67385. }, 0);
  67386. });
  67387. };
  67388. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  67389. var _this = this;
  67390. var gCount = 0;
  67391. triangle.vertices.forEach(function (vertex) {
  67392. var count = 0;
  67393. var vPos = vertex.position;
  67394. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  67395. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  67396. ++count;
  67397. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  67398. ++count;
  67399. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  67400. ++count;
  67401. if (count > 1) {
  67402. ++gCount;
  67403. }
  67404. ;
  67405. });
  67406. if (gCount > 1) {
  67407. console.log(triangle, gCount);
  67408. }
  67409. return gCount > 1;
  67410. };
  67411. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  67412. var _this = this;
  67413. var targetCount = ~~(this.triangles.length * settings.quality);
  67414. var deletedTriangles = 0;
  67415. var triangleCount = this.triangles.length;
  67416. var iterationFunction = function (iteration, callback) {
  67417. setTimeout(function () {
  67418. if (iteration % 5 === 0) {
  67419. _this.updateMesh(iteration === 0);
  67420. }
  67421. for (var i = 0; i < _this.triangles.length; ++i) {
  67422. _this.triangles[i].isDirty = false;
  67423. }
  67424. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  67425. var trianglesIterator = function (i) {
  67426. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  67427. var t = _this.triangles[tIdx];
  67428. if (!t)
  67429. return;
  67430. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  67431. return;
  67432. }
  67433. for (var j = 0; j < 3; ++j) {
  67434. if (t.error[j] < threshold) {
  67435. var deleted0 = [];
  67436. var deleted1 = [];
  67437. var v0 = t.vertices[j];
  67438. var v1 = t.vertices[(j + 1) % 3];
  67439. if (v0.isBorder || v1.isBorder)
  67440. continue;
  67441. var p = BABYLON.Vector3.Zero();
  67442. var n = BABYLON.Vector3.Zero();
  67443. var uv = BABYLON.Vector2.Zero();
  67444. var color = new BABYLON.Color4(0, 0, 0, 1);
  67445. _this.calculateError(v0, v1, p, n, uv, color);
  67446. var delTr = [];
  67447. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  67448. continue;
  67449. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  67450. continue;
  67451. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  67452. continue;
  67453. var uniqueArray = [];
  67454. delTr.forEach(function (deletedT) {
  67455. if (uniqueArray.indexOf(deletedT) === -1) {
  67456. deletedT.deletePending = true;
  67457. uniqueArray.push(deletedT);
  67458. }
  67459. });
  67460. if (uniqueArray.length % 2 !== 0) {
  67461. continue;
  67462. }
  67463. v0.q = v1.q.add(v0.q);
  67464. v0.updatePosition(p);
  67465. var tStart = _this.references.length;
  67466. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  67467. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  67468. var tCount = _this.references.length - tStart;
  67469. if (tCount <= v0.triangleCount) {
  67470. if (tCount) {
  67471. for (var c = 0; c < tCount; c++) {
  67472. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  67473. }
  67474. }
  67475. }
  67476. else {
  67477. v0.triangleStart = tStart;
  67478. }
  67479. v0.triangleCount = tCount;
  67480. break;
  67481. }
  67482. }
  67483. };
  67484. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  67485. }, 0);
  67486. };
  67487. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  67488. if (triangleCount - deletedTriangles <= targetCount)
  67489. loop.breakLoop();
  67490. else {
  67491. iterationFunction(loop.index, function () {
  67492. loop.executeNext();
  67493. });
  67494. }
  67495. }, function () {
  67496. setTimeout(function () {
  67497. //reconstruct this part of the mesh
  67498. _this.reconstructMesh(submeshIndex);
  67499. successCallback();
  67500. }, 0);
  67501. });
  67502. };
  67503. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  67504. var _this = this;
  67505. this.vertices = [];
  67506. this.triangles = [];
  67507. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67508. var indices = this._mesh.getIndices();
  67509. var submesh = this._mesh.subMeshes[submeshIndex];
  67510. var findInVertices = function (positionToSearch) {
  67511. if (optimizeMesh) {
  67512. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  67513. if (_this.vertices[ii].position.equals(positionToSearch)) {
  67514. return _this.vertices[ii];
  67515. }
  67516. }
  67517. }
  67518. return null;
  67519. };
  67520. var vertexReferences = [];
  67521. var vertexInit = function (i) {
  67522. var offset = i + submesh.verticesStart;
  67523. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  67524. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  67525. vertex.originalOffsets.push(offset);
  67526. if (vertex.id === _this.vertices.length) {
  67527. _this.vertices.push(vertex);
  67528. }
  67529. vertexReferences.push(vertex.id);
  67530. };
  67531. //var totalVertices = mesh.getTotalVertices();
  67532. var totalVertices = submesh.verticesCount;
  67533. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  67534. var indicesInit = function (i) {
  67535. var offset = (submesh.indexStart / 3) + i;
  67536. var pos = (offset * 3);
  67537. var i0 = indices[pos + 0];
  67538. var i1 = indices[pos + 1];
  67539. var i2 = indices[pos + 2];
  67540. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  67541. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  67542. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  67543. var triangle = new DecimationTriangle([v0, v1, v2]);
  67544. triangle.originalOffset = pos;
  67545. _this.triangles.push(triangle);
  67546. };
  67547. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  67548. _this.init(callback);
  67549. });
  67550. });
  67551. };
  67552. QuadraticErrorSimplification.prototype.init = function (callback) {
  67553. var _this = this;
  67554. var triangleInit1 = function (i) {
  67555. var t = _this.triangles[i];
  67556. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  67557. for (var j = 0; j < 3; j++) {
  67558. 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))));
  67559. }
  67560. };
  67561. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  67562. var triangleInit2 = function (i) {
  67563. var t = _this.triangles[i];
  67564. for (var j = 0; j < 3; ++j) {
  67565. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  67566. }
  67567. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67568. };
  67569. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  67570. _this.initialized = true;
  67571. callback();
  67572. });
  67573. });
  67574. };
  67575. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  67576. var newTriangles = [];
  67577. var i;
  67578. for (i = 0; i < this.vertices.length; ++i) {
  67579. this.vertices[i].triangleCount = 0;
  67580. }
  67581. var t;
  67582. var j;
  67583. for (i = 0; i < this.triangles.length; ++i) {
  67584. if (!this.triangles[i].deleted) {
  67585. t = this.triangles[i];
  67586. for (j = 0; j < 3; ++j) {
  67587. t.vertices[j].triangleCount = 1;
  67588. }
  67589. newTriangles.push(t);
  67590. }
  67591. }
  67592. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  67593. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  67594. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  67595. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  67596. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67597. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67598. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67599. var vertexCount = 0;
  67600. for (i = 0; i < this.vertices.length; ++i) {
  67601. var vertex = this.vertices[i];
  67602. vertex.id = vertexCount;
  67603. if (vertex.triangleCount) {
  67604. vertex.originalOffsets.forEach(function (originalOffset) {
  67605. newPositionData.push(vertex.position.x);
  67606. newPositionData.push(vertex.position.y);
  67607. newPositionData.push(vertex.position.z);
  67608. newNormalData.push(normalData[originalOffset * 3]);
  67609. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  67610. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  67611. if (uvs && uvs.length) {
  67612. newUVsData.push(uvs[(originalOffset * 2)]);
  67613. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  67614. }
  67615. else if (colorsData && colorsData.length) {
  67616. newColorsData.push(colorsData[(originalOffset * 4)]);
  67617. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  67618. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  67619. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  67620. }
  67621. ++vertexCount;
  67622. });
  67623. }
  67624. }
  67625. var startingIndex = this._reconstructedMesh.getTotalIndices();
  67626. var startingVertex = this._reconstructedMesh.getTotalVertices();
  67627. var submeshesArray = this._reconstructedMesh.subMeshes;
  67628. this._reconstructedMesh.subMeshes = [];
  67629. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  67630. var originalIndices = this._mesh.getIndices();
  67631. for (i = 0; i < newTriangles.length; ++i) {
  67632. t = newTriangles[i]; //now get the new referencing point for each vertex
  67633. [0, 1, 2].forEach(function (idx) {
  67634. var id = originalIndices[t.originalOffset + idx];
  67635. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  67636. if (offset < 0)
  67637. offset = 0;
  67638. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  67639. });
  67640. }
  67641. //overwriting the old vertex buffers and indices.
  67642. this._reconstructedMesh.setIndices(newIndicesArray);
  67643. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  67644. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  67645. if (newUVsData.length > 0)
  67646. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  67647. if (newColorsData.length > 0)
  67648. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  67649. //create submesh
  67650. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  67651. if (submeshIndex > 0) {
  67652. this._reconstructedMesh.subMeshes = [];
  67653. submeshesArray.forEach(function (submesh) {
  67654. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  67655. });
  67656. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  67657. }
  67658. };
  67659. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  67660. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  67661. this._reconstructedMesh.material = this._mesh.material;
  67662. this._reconstructedMesh.parent = this._mesh.parent;
  67663. this._reconstructedMesh.isVisible = false;
  67664. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  67665. };
  67666. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  67667. for (var i = 0; i < vertex1.triangleCount; ++i) {
  67668. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  67669. if (t.deleted)
  67670. continue;
  67671. var s = this.references[vertex1.triangleStart + i].vertexId;
  67672. var v1 = t.vertices[(s + 1) % 3];
  67673. var v2 = t.vertices[(s + 2) % 3];
  67674. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  67675. deletedArray[i] = true;
  67676. delTr.push(t);
  67677. continue;
  67678. }
  67679. var d1 = v1.position.subtract(point);
  67680. d1 = d1.normalize();
  67681. var d2 = v2.position.subtract(point);
  67682. d2 = d2.normalize();
  67683. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  67684. return true;
  67685. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  67686. deletedArray[i] = false;
  67687. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  67688. return true;
  67689. }
  67690. return false;
  67691. };
  67692. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  67693. var newDeleted = deletedTriangles;
  67694. for (var i = 0; i < vertex.triangleCount; ++i) {
  67695. var ref = this.references[vertex.triangleStart + i];
  67696. var t = this.triangles[ref.triangleId];
  67697. if (t.deleted)
  67698. continue;
  67699. if (deletedArray[i] && t.deletePending) {
  67700. t.deleted = true;
  67701. newDeleted++;
  67702. continue;
  67703. }
  67704. t.vertices[ref.vertexId] = origVertex;
  67705. t.isDirty = true;
  67706. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  67707. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  67708. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  67709. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67710. this.references.push(ref);
  67711. }
  67712. return newDeleted;
  67713. };
  67714. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  67715. for (var i = 0; i < this.vertices.length; ++i) {
  67716. var vCount = [];
  67717. var vId = [];
  67718. var v = this.vertices[i];
  67719. var j;
  67720. for (j = 0; j < v.triangleCount; ++j) {
  67721. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  67722. for (var ii = 0; ii < 3; ii++) {
  67723. var ofs = 0;
  67724. var vv = triangle.vertices[ii];
  67725. while (ofs < vCount.length) {
  67726. if (vId[ofs] === vv.id)
  67727. break;
  67728. ++ofs;
  67729. }
  67730. if (ofs === vCount.length) {
  67731. vCount.push(1);
  67732. vId.push(vv.id);
  67733. }
  67734. else {
  67735. vCount[ofs]++;
  67736. }
  67737. }
  67738. }
  67739. for (j = 0; j < vCount.length; ++j) {
  67740. if (vCount[j] === 1) {
  67741. this.vertices[vId[j]].isBorder = true;
  67742. }
  67743. else {
  67744. this.vertices[vId[j]].isBorder = false;
  67745. }
  67746. }
  67747. }
  67748. };
  67749. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  67750. if (identifyBorders === void 0) { identifyBorders = false; }
  67751. var i;
  67752. if (!identifyBorders) {
  67753. var newTrianglesVector = [];
  67754. for (i = 0; i < this.triangles.length; ++i) {
  67755. if (!this.triangles[i].deleted) {
  67756. newTrianglesVector.push(this.triangles[i]);
  67757. }
  67758. }
  67759. this.triangles = newTrianglesVector;
  67760. }
  67761. for (i = 0; i < this.vertices.length; ++i) {
  67762. this.vertices[i].triangleCount = 0;
  67763. this.vertices[i].triangleStart = 0;
  67764. }
  67765. var t;
  67766. var j;
  67767. var v;
  67768. for (i = 0; i < this.triangles.length; ++i) {
  67769. t = this.triangles[i];
  67770. for (j = 0; j < 3; ++j) {
  67771. v = t.vertices[j];
  67772. v.triangleCount++;
  67773. }
  67774. }
  67775. var tStart = 0;
  67776. for (i = 0; i < this.vertices.length; ++i) {
  67777. this.vertices[i].triangleStart = tStart;
  67778. tStart += this.vertices[i].triangleCount;
  67779. this.vertices[i].triangleCount = 0;
  67780. }
  67781. var newReferences = new Array(this.triangles.length * 3);
  67782. for (i = 0; i < this.triangles.length; ++i) {
  67783. t = this.triangles[i];
  67784. for (j = 0; j < 3; ++j) {
  67785. v = t.vertices[j];
  67786. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  67787. v.triangleCount++;
  67788. }
  67789. }
  67790. this.references = newReferences;
  67791. if (identifyBorders) {
  67792. this.identifyBorder();
  67793. }
  67794. };
  67795. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  67796. var x = point.x;
  67797. var y = point.y;
  67798. var z = point.z;
  67799. 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
  67800. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  67801. };
  67802. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  67803. var q = vertex1.q.add(vertex2.q);
  67804. var border = vertex1.isBorder && vertex2.isBorder;
  67805. var error = 0;
  67806. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  67807. if (qDet !== 0 && !border) {
  67808. if (!pointResult) {
  67809. pointResult = BABYLON.Vector3.Zero();
  67810. }
  67811. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  67812. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  67813. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  67814. error = this.vertexError(q, pointResult);
  67815. }
  67816. else {
  67817. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  67818. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  67819. var error1 = this.vertexError(q, vertex1.position);
  67820. var error2 = this.vertexError(q, vertex2.position);
  67821. var error3 = this.vertexError(q, p3);
  67822. error = Math.min(error1, error2, error3);
  67823. if (error === error1) {
  67824. if (pointResult) {
  67825. pointResult.copyFrom(vertex1.position);
  67826. }
  67827. }
  67828. else if (error === error2) {
  67829. if (pointResult) {
  67830. pointResult.copyFrom(vertex2.position);
  67831. }
  67832. }
  67833. else {
  67834. if (pointResult) {
  67835. pointResult.copyFrom(p3);
  67836. }
  67837. }
  67838. }
  67839. return error;
  67840. };
  67841. return QuadraticErrorSimplification;
  67842. }());
  67843. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  67844. })(BABYLON || (BABYLON = {}));
  67845. //# sourceMappingURL=babylon.meshSimplification.js.map
  67846. var BABYLON;
  67847. (function (BABYLON) {
  67848. var Internals;
  67849. (function (Internals) {
  67850. var MeshLODLevel = (function () {
  67851. function MeshLODLevel(distance, mesh) {
  67852. this.distance = distance;
  67853. this.mesh = mesh;
  67854. }
  67855. return MeshLODLevel;
  67856. }());
  67857. Internals.MeshLODLevel = MeshLODLevel;
  67858. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67859. })(BABYLON || (BABYLON = {}));
  67860. //# sourceMappingURL=babylon.meshLODLevel.js.map
  67861. var BABYLON;
  67862. (function (BABYLON) {
  67863. // Standard optimizations
  67864. var SceneOptimization = (function () {
  67865. function SceneOptimization(priority) {
  67866. if (priority === void 0) { priority = 0; }
  67867. this.priority = priority;
  67868. this.apply = function (scene) {
  67869. return true; // Return true if everything that can be done was applied
  67870. };
  67871. }
  67872. return SceneOptimization;
  67873. }());
  67874. BABYLON.SceneOptimization = SceneOptimization;
  67875. var TextureOptimization = (function (_super) {
  67876. __extends(TextureOptimization, _super);
  67877. function TextureOptimization(priority, maximumSize) {
  67878. if (priority === void 0) { priority = 0; }
  67879. if (maximumSize === void 0) { maximumSize = 1024; }
  67880. var _this = _super.call(this, priority) || this;
  67881. _this.priority = priority;
  67882. _this.maximumSize = maximumSize;
  67883. _this.apply = function (scene) {
  67884. var allDone = true;
  67885. for (var index = 0; index < scene.textures.length; index++) {
  67886. var texture = scene.textures[index];
  67887. if (!texture.canRescale || texture.getContext) {
  67888. continue;
  67889. }
  67890. var currentSize = texture.getSize();
  67891. var maxDimension = Math.max(currentSize.width, currentSize.height);
  67892. if (maxDimension > _this.maximumSize) {
  67893. texture.scale(0.5);
  67894. allDone = false;
  67895. }
  67896. }
  67897. return allDone;
  67898. };
  67899. return _this;
  67900. }
  67901. return TextureOptimization;
  67902. }(SceneOptimization));
  67903. BABYLON.TextureOptimization = TextureOptimization;
  67904. var HardwareScalingOptimization = (function (_super) {
  67905. __extends(HardwareScalingOptimization, _super);
  67906. function HardwareScalingOptimization(priority, maximumScale) {
  67907. if (priority === void 0) { priority = 0; }
  67908. if (maximumScale === void 0) { maximumScale = 2; }
  67909. var _this = _super.call(this, priority) || this;
  67910. _this.priority = priority;
  67911. _this.maximumScale = maximumScale;
  67912. _this._currentScale = 1;
  67913. _this.apply = function (scene) {
  67914. _this._currentScale++;
  67915. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  67916. return _this._currentScale >= _this.maximumScale;
  67917. };
  67918. return _this;
  67919. }
  67920. return HardwareScalingOptimization;
  67921. }(SceneOptimization));
  67922. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  67923. var ShadowsOptimization = (function (_super) {
  67924. __extends(ShadowsOptimization, _super);
  67925. function ShadowsOptimization() {
  67926. var _this = _super !== null && _super.apply(this, arguments) || this;
  67927. _this.apply = function (scene) {
  67928. scene.shadowsEnabled = false;
  67929. return true;
  67930. };
  67931. return _this;
  67932. }
  67933. return ShadowsOptimization;
  67934. }(SceneOptimization));
  67935. BABYLON.ShadowsOptimization = ShadowsOptimization;
  67936. var PostProcessesOptimization = (function (_super) {
  67937. __extends(PostProcessesOptimization, _super);
  67938. function PostProcessesOptimization() {
  67939. var _this = _super !== null && _super.apply(this, arguments) || this;
  67940. _this.apply = function (scene) {
  67941. scene.postProcessesEnabled = false;
  67942. return true;
  67943. };
  67944. return _this;
  67945. }
  67946. return PostProcessesOptimization;
  67947. }(SceneOptimization));
  67948. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  67949. var LensFlaresOptimization = (function (_super) {
  67950. __extends(LensFlaresOptimization, _super);
  67951. function LensFlaresOptimization() {
  67952. var _this = _super !== null && _super.apply(this, arguments) || this;
  67953. _this.apply = function (scene) {
  67954. scene.lensFlaresEnabled = false;
  67955. return true;
  67956. };
  67957. return _this;
  67958. }
  67959. return LensFlaresOptimization;
  67960. }(SceneOptimization));
  67961. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  67962. var ParticlesOptimization = (function (_super) {
  67963. __extends(ParticlesOptimization, _super);
  67964. function ParticlesOptimization() {
  67965. var _this = _super !== null && _super.apply(this, arguments) || this;
  67966. _this.apply = function (scene) {
  67967. scene.particlesEnabled = false;
  67968. return true;
  67969. };
  67970. return _this;
  67971. }
  67972. return ParticlesOptimization;
  67973. }(SceneOptimization));
  67974. BABYLON.ParticlesOptimization = ParticlesOptimization;
  67975. var RenderTargetsOptimization = (function (_super) {
  67976. __extends(RenderTargetsOptimization, _super);
  67977. function RenderTargetsOptimization() {
  67978. var _this = _super !== null && _super.apply(this, arguments) || this;
  67979. _this.apply = function (scene) {
  67980. scene.renderTargetsEnabled = false;
  67981. return true;
  67982. };
  67983. return _this;
  67984. }
  67985. return RenderTargetsOptimization;
  67986. }(SceneOptimization));
  67987. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  67988. var MergeMeshesOptimization = (function (_super) {
  67989. __extends(MergeMeshesOptimization, _super);
  67990. function MergeMeshesOptimization() {
  67991. var _this = _super !== null && _super.apply(this, arguments) || this;
  67992. _this._canBeMerged = function (abstractMesh) {
  67993. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  67994. return false;
  67995. }
  67996. var mesh = abstractMesh;
  67997. if (!mesh.isVisible || !mesh.isEnabled()) {
  67998. return false;
  67999. }
  68000. if (mesh.instances.length > 0) {
  68001. return false;
  68002. }
  68003. if (mesh.skeleton || mesh.hasLODLevels) {
  68004. return false;
  68005. }
  68006. if (mesh.parent) {
  68007. return false;
  68008. }
  68009. return true;
  68010. };
  68011. _this.apply = function (scene, updateSelectionTree) {
  68012. var globalPool = scene.meshes.slice(0);
  68013. var globalLength = globalPool.length;
  68014. for (var index = 0; index < globalLength; index++) {
  68015. var currentPool = new Array();
  68016. var current = globalPool[index];
  68017. // Checks
  68018. if (!_this._canBeMerged(current)) {
  68019. continue;
  68020. }
  68021. currentPool.push(current);
  68022. // Find compatible meshes
  68023. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  68024. var otherMesh = globalPool[subIndex];
  68025. if (!_this._canBeMerged(otherMesh)) {
  68026. continue;
  68027. }
  68028. if (otherMesh.material !== current.material) {
  68029. continue;
  68030. }
  68031. if (otherMesh.checkCollisions !== current.checkCollisions) {
  68032. continue;
  68033. }
  68034. currentPool.push(otherMesh);
  68035. globalLength--;
  68036. globalPool.splice(subIndex, 1);
  68037. subIndex--;
  68038. }
  68039. if (currentPool.length < 2) {
  68040. continue;
  68041. }
  68042. // Merge meshes
  68043. BABYLON.Mesh.MergeMeshes(currentPool);
  68044. }
  68045. if (updateSelectionTree != undefined) {
  68046. if (updateSelectionTree) {
  68047. scene.createOrUpdateSelectionOctree();
  68048. }
  68049. }
  68050. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  68051. scene.createOrUpdateSelectionOctree();
  68052. }
  68053. return true;
  68054. };
  68055. return _this;
  68056. }
  68057. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  68058. get: function () {
  68059. return MergeMeshesOptimization._UpdateSelectionTree;
  68060. },
  68061. set: function (value) {
  68062. MergeMeshesOptimization._UpdateSelectionTree = value;
  68063. },
  68064. enumerable: true,
  68065. configurable: true
  68066. });
  68067. MergeMeshesOptimization._UpdateSelectionTree = false;
  68068. return MergeMeshesOptimization;
  68069. }(SceneOptimization));
  68070. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  68071. // Options
  68072. var SceneOptimizerOptions = (function () {
  68073. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  68074. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  68075. if (trackerDuration === void 0) { trackerDuration = 2000; }
  68076. this.targetFrameRate = targetFrameRate;
  68077. this.trackerDuration = trackerDuration;
  68078. this.optimizations = new Array();
  68079. }
  68080. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  68081. var result = new SceneOptimizerOptions(targetFrameRate);
  68082. var priority = 0;
  68083. result.optimizations.push(new MergeMeshesOptimization(priority));
  68084. result.optimizations.push(new ShadowsOptimization(priority));
  68085. result.optimizations.push(new LensFlaresOptimization(priority));
  68086. // Next priority
  68087. priority++;
  68088. result.optimizations.push(new PostProcessesOptimization(priority));
  68089. result.optimizations.push(new ParticlesOptimization(priority));
  68090. // Next priority
  68091. priority++;
  68092. result.optimizations.push(new TextureOptimization(priority, 1024));
  68093. return result;
  68094. };
  68095. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  68096. var result = new SceneOptimizerOptions(targetFrameRate);
  68097. var priority = 0;
  68098. result.optimizations.push(new MergeMeshesOptimization(priority));
  68099. result.optimizations.push(new ShadowsOptimization(priority));
  68100. result.optimizations.push(new LensFlaresOptimization(priority));
  68101. // Next priority
  68102. priority++;
  68103. result.optimizations.push(new PostProcessesOptimization(priority));
  68104. result.optimizations.push(new ParticlesOptimization(priority));
  68105. // Next priority
  68106. priority++;
  68107. result.optimizations.push(new TextureOptimization(priority, 512));
  68108. // Next priority
  68109. priority++;
  68110. result.optimizations.push(new RenderTargetsOptimization(priority));
  68111. // Next priority
  68112. priority++;
  68113. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  68114. return result;
  68115. };
  68116. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  68117. var result = new SceneOptimizerOptions(targetFrameRate);
  68118. var priority = 0;
  68119. result.optimizations.push(new MergeMeshesOptimization(priority));
  68120. result.optimizations.push(new ShadowsOptimization(priority));
  68121. result.optimizations.push(new LensFlaresOptimization(priority));
  68122. // Next priority
  68123. priority++;
  68124. result.optimizations.push(new PostProcessesOptimization(priority));
  68125. result.optimizations.push(new ParticlesOptimization(priority));
  68126. // Next priority
  68127. priority++;
  68128. result.optimizations.push(new TextureOptimization(priority, 256));
  68129. // Next priority
  68130. priority++;
  68131. result.optimizations.push(new RenderTargetsOptimization(priority));
  68132. // Next priority
  68133. priority++;
  68134. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  68135. return result;
  68136. };
  68137. return SceneOptimizerOptions;
  68138. }());
  68139. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  68140. // Scene optimizer tool
  68141. var SceneOptimizer = (function () {
  68142. function SceneOptimizer() {
  68143. }
  68144. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  68145. // TODO: add an epsilon
  68146. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  68147. if (onSuccess) {
  68148. onSuccess();
  68149. }
  68150. return;
  68151. }
  68152. // Apply current level of optimizations
  68153. var allDone = true;
  68154. var noOptimizationApplied = true;
  68155. for (var index = 0; index < options.optimizations.length; index++) {
  68156. var optimization = options.optimizations[index];
  68157. if (optimization.priority === currentPriorityLevel) {
  68158. noOptimizationApplied = false;
  68159. allDone = allDone && optimization.apply(scene);
  68160. }
  68161. }
  68162. // If no optimization was applied, this is a failure :(
  68163. if (noOptimizationApplied) {
  68164. if (onFailure) {
  68165. onFailure();
  68166. }
  68167. return;
  68168. }
  68169. // If all optimizations were done, move to next level
  68170. if (allDone) {
  68171. currentPriorityLevel++;
  68172. }
  68173. // Let's the system running for a specific amount of time before checking FPS
  68174. scene.executeWhenReady(function () {
  68175. setTimeout(function () {
  68176. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  68177. }, options.trackerDuration);
  68178. });
  68179. };
  68180. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  68181. if (!options) {
  68182. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  68183. }
  68184. // Let's the system running for a specific amount of time before checking FPS
  68185. scene.executeWhenReady(function () {
  68186. setTimeout(function () {
  68187. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  68188. }, options.trackerDuration);
  68189. });
  68190. };
  68191. return SceneOptimizer;
  68192. }());
  68193. BABYLON.SceneOptimizer = SceneOptimizer;
  68194. })(BABYLON || (BABYLON = {}));
  68195. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  68196. var BABYLON;
  68197. (function (BABYLON) {
  68198. var OutlineRenderer = (function () {
  68199. function OutlineRenderer(scene) {
  68200. this.zOffset = 1;
  68201. this._scene = scene;
  68202. }
  68203. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  68204. var _this = this;
  68205. if (useOverlay === void 0) { useOverlay = false; }
  68206. var scene = this._scene;
  68207. var engine = this._scene.getEngine();
  68208. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68209. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  68210. return;
  68211. }
  68212. var mesh = subMesh.getRenderingMesh();
  68213. var material = subMesh.getMaterial();
  68214. engine.enableEffect(this._effect);
  68215. // Logarithmic depth
  68216. if (material.useLogarithmicDepth) {
  68217. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  68218. }
  68219. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  68220. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  68221. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68222. // Bones
  68223. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68224. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68225. }
  68226. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68227. // Alpha test
  68228. if (material && material.needAlphaTesting()) {
  68229. var alphaTexture = material.getAlphaTestTexture();
  68230. if (alphaTexture) {
  68231. this._effect.setTexture("diffuseSampler", alphaTexture);
  68232. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68233. }
  68234. }
  68235. engine.setZOffset(-this.zOffset);
  68236. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  68237. engine.setZOffset(0);
  68238. };
  68239. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  68240. var defines = [];
  68241. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68242. var mesh = subMesh.getMesh();
  68243. var material = subMesh.getMaterial();
  68244. if (material) {
  68245. // Alpha test
  68246. if (material.needAlphaTesting()) {
  68247. defines.push("#define ALPHATEST");
  68248. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68249. attribs.push(BABYLON.VertexBuffer.UVKind);
  68250. defines.push("#define UV1");
  68251. }
  68252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68253. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68254. defines.push("#define UV2");
  68255. }
  68256. }
  68257. //Logarithmic depth
  68258. if (material.useLogarithmicDepth) {
  68259. defines.push("#define LOGARITHMICDEPTH");
  68260. }
  68261. }
  68262. // Bones
  68263. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68264. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68265. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68266. if (mesh.numBoneInfluencers > 4) {
  68267. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68268. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68269. }
  68270. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68271. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68272. }
  68273. else {
  68274. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68275. }
  68276. // Instances
  68277. if (useInstances) {
  68278. defines.push("#define INSTANCES");
  68279. attribs.push("world0");
  68280. attribs.push("world1");
  68281. attribs.push("world2");
  68282. attribs.push("world3");
  68283. }
  68284. // Get correct effect
  68285. var join = defines.join("\n");
  68286. if (this._cachedDefines !== join) {
  68287. this._cachedDefines = join;
  68288. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  68289. }
  68290. return this._effect.isReady();
  68291. };
  68292. return OutlineRenderer;
  68293. }());
  68294. BABYLON.OutlineRenderer = OutlineRenderer;
  68295. })(BABYLON || (BABYLON = {}));
  68296. //# sourceMappingURL=babylon.outlineRenderer.js.map
  68297. var BABYLON;
  68298. (function (BABYLON) {
  68299. var FaceAdjacencies = (function () {
  68300. function FaceAdjacencies() {
  68301. this.edges = new Array();
  68302. this.edgesConnectedCount = 0;
  68303. }
  68304. return FaceAdjacencies;
  68305. }());
  68306. var EdgesRenderer = (function () {
  68307. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  68308. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  68309. if (epsilon === void 0) { epsilon = 0.95; }
  68310. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  68311. this.edgesWidthScalerForOrthographic = 1000.0;
  68312. this.edgesWidthScalerForPerspective = 50.0;
  68313. this._linesPositions = new Array();
  68314. this._linesNormals = new Array();
  68315. this._linesIndices = new Array();
  68316. this._buffers = {};
  68317. this._checkVerticesInsteadOfIndices = false;
  68318. this._source = source;
  68319. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  68320. this._epsilon = epsilon;
  68321. this._prepareRessources();
  68322. this._generateEdgesLines();
  68323. }
  68324. EdgesRenderer.prototype._prepareRessources = function () {
  68325. if (this._lineShader) {
  68326. return;
  68327. }
  68328. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  68329. attributes: ["position", "normal"],
  68330. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  68331. });
  68332. this._lineShader.disableDepthWrite = true;
  68333. this._lineShader.backFaceCulling = false;
  68334. };
  68335. EdgesRenderer.prototype._rebuild = function () {
  68336. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68337. if (buffer) {
  68338. buffer._rebuild();
  68339. }
  68340. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68341. if (buffer) {
  68342. buffer._rebuild();
  68343. }
  68344. var scene = this._source.getScene();
  68345. var engine = scene.getEngine();
  68346. this._ib = engine.createIndexBuffer(this._linesIndices);
  68347. };
  68348. EdgesRenderer.prototype.dispose = function () {
  68349. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68350. if (buffer) {
  68351. buffer.dispose();
  68352. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  68353. }
  68354. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68355. if (buffer) {
  68356. buffer.dispose();
  68357. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  68358. }
  68359. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  68360. this._lineShader.dispose();
  68361. };
  68362. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  68363. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  68364. return 0;
  68365. }
  68366. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  68367. return 1;
  68368. }
  68369. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  68370. return 2;
  68371. }
  68372. return -1;
  68373. };
  68374. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  68375. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  68376. return 0;
  68377. }
  68378. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  68379. return 1;
  68380. }
  68381. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  68382. return 2;
  68383. }
  68384. return -1;
  68385. };
  68386. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  68387. var needToCreateLine;
  68388. if (edge === undefined) {
  68389. needToCreateLine = true;
  68390. }
  68391. else {
  68392. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  68393. needToCreateLine = dotProduct < this._epsilon;
  68394. }
  68395. if (needToCreateLine) {
  68396. var offset = this._linesPositions.length / 3;
  68397. var normal = p0.subtract(p1);
  68398. normal.normalize();
  68399. // Positions
  68400. this._linesPositions.push(p0.x);
  68401. this._linesPositions.push(p0.y);
  68402. this._linesPositions.push(p0.z);
  68403. this._linesPositions.push(p0.x);
  68404. this._linesPositions.push(p0.y);
  68405. this._linesPositions.push(p0.z);
  68406. this._linesPositions.push(p1.x);
  68407. this._linesPositions.push(p1.y);
  68408. this._linesPositions.push(p1.z);
  68409. this._linesPositions.push(p1.x);
  68410. this._linesPositions.push(p1.y);
  68411. this._linesPositions.push(p1.z);
  68412. // Normals
  68413. this._linesNormals.push(p1.x);
  68414. this._linesNormals.push(p1.y);
  68415. this._linesNormals.push(p1.z);
  68416. this._linesNormals.push(-1);
  68417. this._linesNormals.push(p1.x);
  68418. this._linesNormals.push(p1.y);
  68419. this._linesNormals.push(p1.z);
  68420. this._linesNormals.push(1);
  68421. this._linesNormals.push(p0.x);
  68422. this._linesNormals.push(p0.y);
  68423. this._linesNormals.push(p0.z);
  68424. this._linesNormals.push(-1);
  68425. this._linesNormals.push(p0.x);
  68426. this._linesNormals.push(p0.y);
  68427. this._linesNormals.push(p0.z);
  68428. this._linesNormals.push(1);
  68429. // Indices
  68430. this._linesIndices.push(offset);
  68431. this._linesIndices.push(offset + 1);
  68432. this._linesIndices.push(offset + 2);
  68433. this._linesIndices.push(offset);
  68434. this._linesIndices.push(offset + 2);
  68435. this._linesIndices.push(offset + 3);
  68436. }
  68437. };
  68438. EdgesRenderer.prototype._generateEdgesLines = function () {
  68439. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68440. var indices = this._source.getIndices();
  68441. // First let's find adjacencies
  68442. var adjacencies = new Array();
  68443. var faceNormals = new Array();
  68444. var index;
  68445. var faceAdjacencies;
  68446. // Prepare faces
  68447. for (index = 0; index < indices.length; index += 3) {
  68448. faceAdjacencies = new FaceAdjacencies();
  68449. var p0Index = indices[index];
  68450. var p1Index = indices[index + 1];
  68451. var p2Index = indices[index + 2];
  68452. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  68453. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  68454. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  68455. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  68456. faceNormal.normalize();
  68457. faceNormals.push(faceNormal);
  68458. adjacencies.push(faceAdjacencies);
  68459. }
  68460. // Scan
  68461. for (index = 0; index < adjacencies.length; index++) {
  68462. faceAdjacencies = adjacencies[index];
  68463. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  68464. var otherFaceAdjacencies = adjacencies[otherIndex];
  68465. if (faceAdjacencies.edgesConnectedCount === 3) {
  68466. break;
  68467. }
  68468. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  68469. continue;
  68470. }
  68471. var otherP0 = indices[otherIndex * 3];
  68472. var otherP1 = indices[otherIndex * 3 + 1];
  68473. var otherP2 = indices[otherIndex * 3 + 2];
  68474. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  68475. var otherEdgeIndex;
  68476. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  68477. continue;
  68478. }
  68479. switch (edgeIndex) {
  68480. case 0:
  68481. if (this._checkVerticesInsteadOfIndices) {
  68482. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68483. }
  68484. else {
  68485. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  68486. }
  68487. break;
  68488. case 1:
  68489. if (this._checkVerticesInsteadOfIndices) {
  68490. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68491. }
  68492. else {
  68493. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  68494. }
  68495. break;
  68496. case 2:
  68497. if (this._checkVerticesInsteadOfIndices) {
  68498. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68499. }
  68500. else {
  68501. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  68502. }
  68503. break;
  68504. }
  68505. if (otherEdgeIndex === -1) {
  68506. continue;
  68507. }
  68508. faceAdjacencies.edges[edgeIndex] = otherIndex;
  68509. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  68510. faceAdjacencies.edgesConnectedCount++;
  68511. otherFaceAdjacencies.edgesConnectedCount++;
  68512. if (faceAdjacencies.edgesConnectedCount === 3) {
  68513. break;
  68514. }
  68515. }
  68516. }
  68517. }
  68518. // Create lines
  68519. for (index = 0; index < adjacencies.length; index++) {
  68520. // 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
  68521. var current = adjacencies[index];
  68522. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  68523. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  68524. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  68525. }
  68526. // Merge into a single mesh
  68527. var engine = this._source.getScene().getEngine();
  68528. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  68529. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  68530. this._ib = engine.createIndexBuffer(this._linesIndices);
  68531. this._indicesCount = this._linesIndices.length;
  68532. };
  68533. EdgesRenderer.prototype.render = function () {
  68534. if (!this._lineShader.isReady()) {
  68535. return;
  68536. }
  68537. var scene = this._source.getScene();
  68538. var engine = scene.getEngine();
  68539. this._lineShader._preBind();
  68540. // VBOs
  68541. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  68542. scene.resetCachedMaterial();
  68543. this._lineShader.setColor4("color", this._source.edgesColor);
  68544. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  68545. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  68546. }
  68547. else {
  68548. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  68549. }
  68550. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  68551. this._lineShader.bind(this._source.getWorldMatrix());
  68552. // Draw order
  68553. engine.draw(true, 0, this._indicesCount);
  68554. this._lineShader.unbind();
  68555. engine.setDepthWrite(true);
  68556. };
  68557. return EdgesRenderer;
  68558. }());
  68559. BABYLON.EdgesRenderer = EdgesRenderer;
  68560. })(BABYLON || (BABYLON = {}));
  68561. //# sourceMappingURL=babylon.edgesRenderer.js.map
  68562. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  68563. /// <reference path="..\Math\babylon.math.ts" />
  68564. var BABYLON;
  68565. (function (BABYLON) {
  68566. /**
  68567. * Special Glow Blur post process only blurring the alpha channel
  68568. * It enforces keeping the most luminous color in the color channel.
  68569. */
  68570. var GlowBlurPostProcess = (function (_super) {
  68571. __extends(GlowBlurPostProcess, _super);
  68572. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  68573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68574. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  68575. _this.direction = direction;
  68576. _this.kernel = kernel;
  68577. _this.onApplyObservable.add(function (effect) {
  68578. effect.setFloat2("screenSize", _this.width, _this.height);
  68579. effect.setVector2("direction", _this.direction);
  68580. effect.setFloat("blurWidth", _this.kernel);
  68581. });
  68582. return _this;
  68583. }
  68584. return GlowBlurPostProcess;
  68585. }(BABYLON.PostProcess));
  68586. /**
  68587. * The highlight layer Helps adding a glow effect around a mesh.
  68588. *
  68589. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  68590. * glowy meshes to your scene.
  68591. *
  68592. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  68593. */
  68594. var HighlightLayer = (function () {
  68595. /**
  68596. * Instantiates a new highlight Layer and references it to the scene..
  68597. * @param name The name of the layer
  68598. * @param scene The scene to use the layer in
  68599. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  68600. */
  68601. function HighlightLayer(name, scene, options) {
  68602. this.name = name;
  68603. this._vertexBuffers = {};
  68604. this._mainTextureDesiredSize = { width: 0, height: 0 };
  68605. this._meshes = {};
  68606. this._maxSize = 0;
  68607. this._shouldRender = false;
  68608. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  68609. this._excludedMeshes = {};
  68610. /**
  68611. * Specifies whether or not the inner glow is ACTIVE in the layer.
  68612. */
  68613. this.innerGlow = true;
  68614. /**
  68615. * Specifies whether or not the outer glow is ACTIVE in the layer.
  68616. */
  68617. this.outerGlow = true;
  68618. /**
  68619. * Specifies wether the highlight layer is enabled or not.
  68620. */
  68621. this.isEnabled = true;
  68622. /**
  68623. * An event triggered when the highlight layer has been disposed.
  68624. * @type {BABYLON.Observable}
  68625. */
  68626. this.onDisposeObservable = new BABYLON.Observable();
  68627. /**
  68628. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  68629. * @type {BABYLON.Observable}
  68630. */
  68631. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  68632. /**
  68633. * An event triggered when the highlight layer is being blurred.
  68634. * @type {BABYLON.Observable}
  68635. */
  68636. this.onBeforeBlurObservable = new BABYLON.Observable();
  68637. /**
  68638. * An event triggered when the highlight layer has been blurred.
  68639. * @type {BABYLON.Observable}
  68640. */
  68641. this.onAfterBlurObservable = new BABYLON.Observable();
  68642. /**
  68643. * An event triggered when the glowing blurred texture is being merged in the scene.
  68644. * @type {BABYLON.Observable}
  68645. */
  68646. this.onBeforeComposeObservable = new BABYLON.Observable();
  68647. /**
  68648. * An event triggered when the glowing blurred texture has been merged in the scene.
  68649. * @type {BABYLON.Observable}
  68650. */
  68651. this.onAfterComposeObservable = new BABYLON.Observable();
  68652. /**
  68653. * An event triggered when the highlight layer changes its size.
  68654. * @type {BABYLON.Observable}
  68655. */
  68656. this.onSizeChangedObservable = new BABYLON.Observable();
  68657. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68658. var engine = scene.getEngine();
  68659. this._engine = engine;
  68660. this._maxSize = this._engine.getCaps().maxTextureSize;
  68661. this._scene.highlightLayers.push(this);
  68662. // Warn on stencil.
  68663. if (!this._engine.isStencilEnable) {
  68664. 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 }");
  68665. }
  68666. // Adapt options
  68667. this._options = options || {
  68668. mainTextureRatio: 0.5,
  68669. blurTextureSizeRatio: 0.5,
  68670. blurHorizontalSize: 1.0,
  68671. blurVerticalSize: 1.0,
  68672. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  68673. };
  68674. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  68675. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  68676. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  68677. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  68678. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  68679. // VBO
  68680. var vertices = [];
  68681. vertices.push(1, 1);
  68682. vertices.push(-1, 1);
  68683. vertices.push(-1, -1);
  68684. vertices.push(1, -1);
  68685. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68686. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  68687. this._createIndexBuffer();
  68688. // Effect
  68689. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  68690. // Render target
  68691. this.setMainTextureSize();
  68692. // Create Textures and post processes
  68693. this.createTextureAndPostProcesses();
  68694. }
  68695. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  68696. /**
  68697. * Gets the horizontal size of the blur.
  68698. */
  68699. get: function () {
  68700. return this._horizontalBlurPostprocess.kernel;
  68701. },
  68702. /**
  68703. * Specifies the horizontal size of the blur.
  68704. */
  68705. set: function (value) {
  68706. this._horizontalBlurPostprocess.kernel = value;
  68707. },
  68708. enumerable: true,
  68709. configurable: true
  68710. });
  68711. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  68712. /**
  68713. * Gets the vertical size of the blur.
  68714. */
  68715. get: function () {
  68716. return this._verticalBlurPostprocess.kernel;
  68717. },
  68718. /**
  68719. * Specifies the vertical size of the blur.
  68720. */
  68721. set: function (value) {
  68722. this._verticalBlurPostprocess.kernel = value;
  68723. },
  68724. enumerable: true,
  68725. configurable: true
  68726. });
  68727. Object.defineProperty(HighlightLayer.prototype, "camera", {
  68728. /**
  68729. * Gets the camera attached to the layer.
  68730. */
  68731. get: function () {
  68732. return this._options.camera;
  68733. },
  68734. enumerable: true,
  68735. configurable: true
  68736. });
  68737. HighlightLayer.prototype._createIndexBuffer = function () {
  68738. var engine = this._scene.getEngine();
  68739. // Indices
  68740. var indices = [];
  68741. indices.push(0);
  68742. indices.push(1);
  68743. indices.push(2);
  68744. indices.push(0);
  68745. indices.push(2);
  68746. indices.push(3);
  68747. this._indexBuffer = engine.createIndexBuffer(indices);
  68748. };
  68749. HighlightLayer.prototype._rebuild = function () {
  68750. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  68751. this._createIndexBuffer();
  68752. };
  68753. /**
  68754. * Creates the render target textures and post processes used in the highlight layer.
  68755. */
  68756. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  68757. var _this = this;
  68758. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  68759. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  68760. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  68761. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  68762. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  68763. width: this._mainTextureDesiredSize.width,
  68764. height: this._mainTextureDesiredSize.height
  68765. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68766. this._mainTexture.activeCamera = this._options.camera;
  68767. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68768. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68769. this._mainTexture.anisotropicFilteringLevel = 1;
  68770. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68771. this._mainTexture.renderParticles = false;
  68772. this._mainTexture.renderList = null;
  68773. this._mainTexture.ignoreCameraViewport = true;
  68774. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  68775. width: blurTextureWidth,
  68776. height: blurTextureHeight
  68777. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68778. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68779. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68780. this._blurTexture.anisotropicFilteringLevel = 16;
  68781. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68782. this._blurTexture.renderParticles = false;
  68783. this._blurTexture.ignoreCameraViewport = true;
  68784. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68785. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  68786. effect.setTexture("textureSampler", _this._mainTexture);
  68787. });
  68788. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  68789. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68790. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  68791. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68792. });
  68793. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68794. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  68795. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68796. });
  68797. }
  68798. else {
  68799. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68800. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  68801. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68802. });
  68803. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68804. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  68805. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68806. });
  68807. }
  68808. this._mainTexture.onAfterUnbindObservable.add(function () {
  68809. _this.onBeforeBlurObservable.notifyObservers(_this);
  68810. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  68811. _this.onAfterBlurObservable.notifyObservers(_this);
  68812. });
  68813. // Custom render function
  68814. var renderSubMesh = function (subMesh) {
  68815. var mesh = subMesh.getRenderingMesh();
  68816. var scene = _this._scene;
  68817. var engine = scene.getEngine();
  68818. // Culling
  68819. engine.setState(subMesh.getMaterial().backFaceCulling);
  68820. // Managing instances
  68821. var batch = mesh._getInstancesRenderList(subMesh._id);
  68822. if (batch.mustReturn) {
  68823. return;
  68824. }
  68825. // Excluded Mesh
  68826. if (_this._excludedMeshes[mesh.uniqueId]) {
  68827. return;
  68828. }
  68829. ;
  68830. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68831. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  68832. var material = subMesh.getMaterial();
  68833. var emissiveTexture = null;
  68834. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  68835. emissiveTexture = material.emissiveTexture;
  68836. }
  68837. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  68838. engine.enableEffect(_this._glowMapGenerationEffect);
  68839. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  68840. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  68841. if (highlightLayerMesh) {
  68842. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  68843. }
  68844. else {
  68845. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  68846. }
  68847. // Alpha test
  68848. if (material && material.needAlphaTesting()) {
  68849. var alphaTexture = material.getAlphaTestTexture();
  68850. if (alphaTexture) {
  68851. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  68852. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68853. }
  68854. }
  68855. // Glow emissive only
  68856. if (emissiveTexture) {
  68857. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  68858. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  68859. }
  68860. // Bones
  68861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68862. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68863. }
  68864. // Draw
  68865. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  68866. }
  68867. else {
  68868. // Need to reset refresh rate of the shadowMap
  68869. _this._mainTexture.resetRefreshCounter();
  68870. }
  68871. };
  68872. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68873. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  68874. var index;
  68875. var engine = _this._scene.getEngine();
  68876. if (depthOnlySubMeshes.length) {
  68877. engine.setColorWrite(false);
  68878. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68879. renderSubMesh(depthOnlySubMeshes.data[index]);
  68880. }
  68881. engine.setColorWrite(true);
  68882. }
  68883. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68884. renderSubMesh(opaqueSubMeshes.data[index]);
  68885. }
  68886. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68887. renderSubMesh(alphaTestSubMeshes.data[index]);
  68888. }
  68889. for (index = 0; index < transparentSubMeshes.length; index++) {
  68890. renderSubMesh(transparentSubMeshes.data[index]);
  68891. }
  68892. };
  68893. this._mainTexture.onClearObservable.add(function (engine) {
  68894. engine.clear(HighlightLayer.neutralColor, true, true, true);
  68895. });
  68896. };
  68897. /**
  68898. * Checks for the readiness of the element composing the layer.
  68899. * @param subMesh the mesh to check for
  68900. * @param useInstances specify wether or not to use instances to render the mesh
  68901. * @param emissiveTexture the associated emissive texture used to generate the glow
  68902. * @return true if ready otherwise, false
  68903. */
  68904. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  68905. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  68906. return false;
  68907. }
  68908. var defines = [];
  68909. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68910. var mesh = subMesh.getMesh();
  68911. var material = subMesh.getMaterial();
  68912. var uv1 = false;
  68913. var uv2 = false;
  68914. // Alpha test
  68915. if (material && material.needAlphaTesting()) {
  68916. var alphaTexture = material.getAlphaTestTexture();
  68917. if (alphaTexture) {
  68918. defines.push("#define ALPHATEST");
  68919. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  68920. alphaTexture.coordinatesIndex === 1) {
  68921. defines.push("#define DIFFUSEUV2");
  68922. uv2 = true;
  68923. }
  68924. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68925. defines.push("#define DIFFUSEUV1");
  68926. uv1 = true;
  68927. }
  68928. }
  68929. }
  68930. // Emissive
  68931. if (emissiveTexture) {
  68932. defines.push("#define EMISSIVE");
  68933. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  68934. emissiveTexture.coordinatesIndex === 1) {
  68935. defines.push("#define EMISSIVEUV2");
  68936. uv2 = true;
  68937. }
  68938. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68939. defines.push("#define EMISSIVEUV1");
  68940. uv1 = true;
  68941. }
  68942. }
  68943. if (uv1) {
  68944. attribs.push(BABYLON.VertexBuffer.UVKind);
  68945. defines.push("#define UV1");
  68946. }
  68947. if (uv2) {
  68948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68949. defines.push("#define UV2");
  68950. }
  68951. // Bones
  68952. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68953. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68954. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68955. if (mesh.numBoneInfluencers > 4) {
  68956. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68957. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68958. }
  68959. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68960. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68961. }
  68962. else {
  68963. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68964. }
  68965. // Instances
  68966. if (useInstances) {
  68967. defines.push("#define INSTANCES");
  68968. attribs.push("world0");
  68969. attribs.push("world1");
  68970. attribs.push("world2");
  68971. attribs.push("world3");
  68972. }
  68973. // Get correct effect
  68974. var join = defines.join("\n");
  68975. if (this._cachedDefines !== join) {
  68976. this._cachedDefines = join;
  68977. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  68978. }
  68979. return this._glowMapGenerationEffect.isReady();
  68980. };
  68981. /**
  68982. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  68983. */
  68984. HighlightLayer.prototype.render = function () {
  68985. var currentEffect = this._glowMapMergeEffect;
  68986. // Check
  68987. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  68988. return;
  68989. var engine = this._scene.getEngine();
  68990. this.onBeforeComposeObservable.notifyObservers(this);
  68991. // Render
  68992. engine.enableEffect(currentEffect);
  68993. engine.setState(false);
  68994. // Cache
  68995. var previousStencilBuffer = engine.getStencilBuffer();
  68996. var previousStencilFunction = engine.getStencilFunction();
  68997. var previousStencilMask = engine.getStencilMask();
  68998. var previousStencilOperationPass = engine.getStencilOperationPass();
  68999. var previousStencilOperationFail = engine.getStencilOperationFail();
  69000. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  69001. var previousAlphaMode = engine.getAlphaMode();
  69002. // Texture
  69003. currentEffect.setTexture("textureSampler", this._blurTexture);
  69004. // VBOs
  69005. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69006. // Stencil operations
  69007. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  69008. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  69009. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  69010. // Draw order
  69011. engine.setAlphaMode(this._options.alphaBlendingMode);
  69012. engine.setStencilMask(0x00);
  69013. engine.setStencilBuffer(true);
  69014. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  69015. if (this.outerGlow) {
  69016. currentEffect.setFloat("offset", 0);
  69017. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  69018. engine.draw(true, 0, 6);
  69019. }
  69020. if (this.innerGlow) {
  69021. currentEffect.setFloat("offset", 1);
  69022. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  69023. engine.draw(true, 0, 6);
  69024. }
  69025. // Restore Cache
  69026. engine.setStencilFunction(previousStencilFunction);
  69027. engine.setStencilMask(previousStencilMask);
  69028. engine.setAlphaMode(previousAlphaMode);
  69029. engine.setStencilBuffer(previousStencilBuffer);
  69030. engine.setStencilOperationPass(previousStencilOperationPass);
  69031. engine.setStencilOperationFail(previousStencilOperationFail);
  69032. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  69033. engine._stencilState.reset();
  69034. this.onAfterComposeObservable.notifyObservers(this);
  69035. // Handle size changes.
  69036. var size = this._mainTexture.getSize();
  69037. this.setMainTextureSize();
  69038. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  69039. // Recreate RTT and post processes on size change.
  69040. this.onSizeChangedObservable.notifyObservers(this);
  69041. this.disposeTextureAndPostProcesses();
  69042. this.createTextureAndPostProcesses();
  69043. }
  69044. };
  69045. /**
  69046. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  69047. * @param mesh The mesh to exclude from the highlight layer
  69048. */
  69049. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  69050. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69051. if (!meshExcluded) {
  69052. this._excludedMeshes[mesh.uniqueId] = {
  69053. mesh: mesh,
  69054. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  69055. mesh.getEngine().setStencilBuffer(false);
  69056. }),
  69057. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  69058. mesh.getEngine().setStencilBuffer(true);
  69059. }),
  69060. };
  69061. }
  69062. };
  69063. /**
  69064. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  69065. * @param mesh The mesh to highlight
  69066. */
  69067. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  69068. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69069. if (meshExcluded) {
  69070. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  69071. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  69072. }
  69073. this._excludedMeshes[mesh.uniqueId] = undefined;
  69074. };
  69075. /**
  69076. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  69077. * @param mesh The mesh to highlight
  69078. * @param color The color of the highlight
  69079. * @param glowEmissiveOnly Extract the glow from the emissive texture
  69080. */
  69081. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  69082. var _this = this;
  69083. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  69084. var meshHighlight = this._meshes[mesh.uniqueId];
  69085. if (meshHighlight) {
  69086. meshHighlight.color = color;
  69087. }
  69088. else {
  69089. this._meshes[mesh.uniqueId] = {
  69090. mesh: mesh,
  69091. color: color,
  69092. // Lambda required for capture due to Observable this context
  69093. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  69094. if (_this._excludedMeshes[mesh.uniqueId]) {
  69095. _this.defaultStencilReference(mesh);
  69096. }
  69097. else {
  69098. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  69099. }
  69100. }),
  69101. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  69102. glowEmissiveOnly: glowEmissiveOnly
  69103. };
  69104. }
  69105. this._shouldRender = true;
  69106. };
  69107. /**
  69108. * Remove a mesh from the highlight layer in order to make it stop glowing.
  69109. * @param mesh The mesh to highlight
  69110. */
  69111. HighlightLayer.prototype.removeMesh = function (mesh) {
  69112. var meshHighlight = this._meshes[mesh.uniqueId];
  69113. if (meshHighlight) {
  69114. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69115. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69116. }
  69117. this._meshes[mesh.uniqueId] = undefined;
  69118. this._shouldRender = false;
  69119. for (var meshHighlightToCheck in this._meshes) {
  69120. if (meshHighlightToCheck) {
  69121. this._shouldRender = true;
  69122. break;
  69123. }
  69124. }
  69125. };
  69126. /**
  69127. * Returns true if the layer contains information to display, otherwise false.
  69128. */
  69129. HighlightLayer.prototype.shouldRender = function () {
  69130. return this.isEnabled && this._shouldRender;
  69131. };
  69132. /**
  69133. * Sets the main texture desired size which is the closest power of two
  69134. * of the engine canvas size.
  69135. */
  69136. HighlightLayer.prototype.setMainTextureSize = function () {
  69137. if (this._options.mainTextureFixedSize) {
  69138. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  69139. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  69140. }
  69141. else {
  69142. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  69143. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  69144. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  69145. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  69146. }
  69147. };
  69148. /**
  69149. * Force the stencil to the normal expected value for none glowing parts
  69150. */
  69151. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  69152. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  69153. };
  69154. /**
  69155. * Dispose only the render target textures and post process.
  69156. */
  69157. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  69158. this._blurTexture.dispose();
  69159. this._mainTexture.dispose();
  69160. this._downSamplePostprocess.dispose();
  69161. this._horizontalBlurPostprocess.dispose();
  69162. this._verticalBlurPostprocess.dispose();
  69163. };
  69164. /**
  69165. * Dispose the highlight layer and free resources.
  69166. */
  69167. HighlightLayer.prototype.dispose = function () {
  69168. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69169. if (vertexBuffer) {
  69170. vertexBuffer.dispose();
  69171. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69172. }
  69173. if (this._indexBuffer) {
  69174. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69175. this._indexBuffer = null;
  69176. }
  69177. // Clean textures and post processes
  69178. this.disposeTextureAndPostProcesses();
  69179. // Clean mesh references
  69180. for (var id in this._meshes) {
  69181. var meshHighlight = this._meshes[id];
  69182. if (meshHighlight && meshHighlight.mesh) {
  69183. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69184. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69185. }
  69186. }
  69187. this._meshes = null;
  69188. for (var id in this._excludedMeshes) {
  69189. var meshHighlight = this._excludedMeshes[id];
  69190. if (meshHighlight) {
  69191. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  69192. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  69193. }
  69194. }
  69195. this._excludedMeshes = null;
  69196. // Remove from scene
  69197. var index = this._scene.highlightLayers.indexOf(this, 0);
  69198. if (index > -1) {
  69199. this._scene.highlightLayers.splice(index, 1);
  69200. }
  69201. // Callback
  69202. this.onDisposeObservable.notifyObservers(this);
  69203. this.onDisposeObservable.clear();
  69204. this.onBeforeRenderMainTextureObservable.clear();
  69205. this.onBeforeBlurObservable.clear();
  69206. this.onBeforeComposeObservable.clear();
  69207. this.onAfterComposeObservable.clear();
  69208. this.onSizeChangedObservable.clear();
  69209. };
  69210. /**
  69211. * The neutral color used during the preparation of the glow effect.
  69212. * This is black by default as the blend operation is a blend operation.
  69213. */
  69214. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  69215. /**
  69216. * Stencil value used for glowing meshes.
  69217. */
  69218. HighlightLayer.glowingMeshStencilReference = 0x02;
  69219. /**
  69220. * Stencil value used for the other meshes in the scene.
  69221. */
  69222. HighlightLayer.normalMeshStencilReference = 0x01;
  69223. return HighlightLayer;
  69224. }());
  69225. BABYLON.HighlightLayer = HighlightLayer;
  69226. })(BABYLON || (BABYLON = {}));
  69227. //# sourceMappingURL=babylon.highlightlayer.js.map
  69228. var BABYLON;
  69229. (function (BABYLON) {
  69230. var MeshAssetTask = (function () {
  69231. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  69232. this.name = name;
  69233. this.meshesNames = meshesNames;
  69234. this.rootUrl = rootUrl;
  69235. this.sceneFilename = sceneFilename;
  69236. this.isCompleted = false;
  69237. }
  69238. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69239. var _this = this;
  69240. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  69241. _this.loadedMeshes = meshes;
  69242. _this.loadedParticleSystems = particleSystems;
  69243. _this.loadedSkeletons = skeletons;
  69244. _this.isCompleted = true;
  69245. if (_this.onSuccess) {
  69246. _this.onSuccess(_this);
  69247. }
  69248. onSuccess();
  69249. }, null, function () {
  69250. if (_this.onError) {
  69251. _this.onError(_this);
  69252. }
  69253. onError();
  69254. });
  69255. };
  69256. return MeshAssetTask;
  69257. }());
  69258. BABYLON.MeshAssetTask = MeshAssetTask;
  69259. var TextFileAssetTask = (function () {
  69260. function TextFileAssetTask(name, url) {
  69261. this.name = name;
  69262. this.url = url;
  69263. this.isCompleted = false;
  69264. }
  69265. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69266. var _this = this;
  69267. BABYLON.Tools.LoadFile(this.url, function (data) {
  69268. _this.text = data;
  69269. _this.isCompleted = true;
  69270. if (_this.onSuccess) {
  69271. _this.onSuccess(_this);
  69272. }
  69273. onSuccess();
  69274. }, null, scene.database, false, function () {
  69275. if (_this.onError) {
  69276. _this.onError(_this);
  69277. }
  69278. onError();
  69279. });
  69280. };
  69281. return TextFileAssetTask;
  69282. }());
  69283. BABYLON.TextFileAssetTask = TextFileAssetTask;
  69284. var BinaryFileAssetTask = (function () {
  69285. function BinaryFileAssetTask(name, url) {
  69286. this.name = name;
  69287. this.url = url;
  69288. this.isCompleted = false;
  69289. }
  69290. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69291. var _this = this;
  69292. BABYLON.Tools.LoadFile(this.url, function (data) {
  69293. _this.data = data;
  69294. _this.isCompleted = true;
  69295. if (_this.onSuccess) {
  69296. _this.onSuccess(_this);
  69297. }
  69298. onSuccess();
  69299. }, null, scene.database, true, function () {
  69300. if (_this.onError) {
  69301. _this.onError(_this);
  69302. }
  69303. onError();
  69304. });
  69305. };
  69306. return BinaryFileAssetTask;
  69307. }());
  69308. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  69309. var ImageAssetTask = (function () {
  69310. function ImageAssetTask(name, url) {
  69311. this.name = name;
  69312. this.url = url;
  69313. this.isCompleted = false;
  69314. }
  69315. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69316. var _this = this;
  69317. var img = new Image();
  69318. BABYLON.Tools.SetCorsBehavior(this.url, img);
  69319. img.onload = function () {
  69320. _this.image = img;
  69321. _this.isCompleted = true;
  69322. if (_this.onSuccess) {
  69323. _this.onSuccess(_this);
  69324. }
  69325. onSuccess();
  69326. };
  69327. img.onerror = function () {
  69328. if (_this.onError) {
  69329. _this.onError(_this);
  69330. }
  69331. onError();
  69332. };
  69333. img.src = this.url;
  69334. };
  69335. return ImageAssetTask;
  69336. }());
  69337. BABYLON.ImageAssetTask = ImageAssetTask;
  69338. var TextureAssetTask = (function () {
  69339. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  69340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69341. this.name = name;
  69342. this.url = url;
  69343. this.noMipmap = noMipmap;
  69344. this.invertY = invertY;
  69345. this.samplingMode = samplingMode;
  69346. this.isCompleted = false;
  69347. }
  69348. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69349. var _this = this;
  69350. var onload = function () {
  69351. _this.isCompleted = true;
  69352. if (_this.onSuccess) {
  69353. _this.onSuccess(_this);
  69354. }
  69355. onSuccess();
  69356. };
  69357. var onerror = function () {
  69358. if (_this.onError) {
  69359. _this.onError(_this);
  69360. }
  69361. onError();
  69362. };
  69363. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  69364. };
  69365. return TextureAssetTask;
  69366. }());
  69367. BABYLON.TextureAssetTask = TextureAssetTask;
  69368. var CubeTextureAssetTask = (function () {
  69369. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  69370. this.name = name;
  69371. this.url = url;
  69372. this.extensions = extensions;
  69373. this.noMipmap = noMipmap;
  69374. this.files = files;
  69375. this.isCompleted = false;
  69376. }
  69377. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69378. var _this = this;
  69379. var onload = function () {
  69380. _this.isCompleted = true;
  69381. if (_this.onSuccess) {
  69382. _this.onSuccess(_this);
  69383. }
  69384. onSuccess();
  69385. };
  69386. var onerror = function () {
  69387. if (_this.onError) {
  69388. _this.onError(_this);
  69389. }
  69390. onError();
  69391. };
  69392. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  69393. };
  69394. return CubeTextureAssetTask;
  69395. }());
  69396. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  69397. var HDRCubeTextureAssetTask = (function () {
  69398. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69399. if (noMipmap === void 0) { noMipmap = false; }
  69400. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69401. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69402. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69403. this.name = name;
  69404. this.url = url;
  69405. this.size = size;
  69406. this.noMipmap = noMipmap;
  69407. this.generateHarmonics = generateHarmonics;
  69408. this.useInGammaSpace = useInGammaSpace;
  69409. this.usePMREMGenerator = usePMREMGenerator;
  69410. this.isCompleted = false;
  69411. }
  69412. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69413. var _this = this;
  69414. var onload = function () {
  69415. _this.isCompleted = true;
  69416. if (_this.onSuccess) {
  69417. _this.onSuccess(_this);
  69418. }
  69419. onSuccess();
  69420. };
  69421. var onerror = function () {
  69422. if (_this.onError) {
  69423. _this.onError(_this);
  69424. }
  69425. onError();
  69426. };
  69427. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  69428. };
  69429. return HDRCubeTextureAssetTask;
  69430. }());
  69431. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  69432. var AssetsManager = (function () {
  69433. function AssetsManager(scene) {
  69434. this.tasks = new Array();
  69435. this.waitingTasksCount = 0;
  69436. this.useDefaultLoadingScreen = true;
  69437. this._scene = scene;
  69438. }
  69439. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  69440. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  69441. this.tasks.push(task);
  69442. return task;
  69443. };
  69444. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  69445. var task = new TextFileAssetTask(taskName, url);
  69446. this.tasks.push(task);
  69447. return task;
  69448. };
  69449. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  69450. var task = new BinaryFileAssetTask(taskName, url);
  69451. this.tasks.push(task);
  69452. return task;
  69453. };
  69454. AssetsManager.prototype.addImageTask = function (taskName, url) {
  69455. var task = new ImageAssetTask(taskName, url);
  69456. this.tasks.push(task);
  69457. return task;
  69458. };
  69459. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  69460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69461. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  69462. this.tasks.push(task);
  69463. return task;
  69464. };
  69465. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  69466. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  69467. this.tasks.push(task);
  69468. return task;
  69469. };
  69470. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69471. if (noMipmap === void 0) { noMipmap = false; }
  69472. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69473. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69474. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69475. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  69476. this.tasks.push(task);
  69477. return task;
  69478. };
  69479. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  69480. this.waitingTasksCount--;
  69481. if (this.waitingTasksCount === 0) {
  69482. if (this.onFinish) {
  69483. this.onFinish(this.tasks);
  69484. }
  69485. this._scene.getEngine().hideLoadingUI();
  69486. }
  69487. };
  69488. AssetsManager.prototype._runTask = function (task) {
  69489. var _this = this;
  69490. task.run(this._scene, function () {
  69491. if (_this.onTaskSuccess) {
  69492. _this.onTaskSuccess(task);
  69493. }
  69494. _this._decreaseWaitingTasksCount();
  69495. }, function () {
  69496. if (_this.onTaskError) {
  69497. _this.onTaskError(task);
  69498. }
  69499. _this._decreaseWaitingTasksCount();
  69500. });
  69501. };
  69502. AssetsManager.prototype.reset = function () {
  69503. this.tasks = new Array();
  69504. return this;
  69505. };
  69506. AssetsManager.prototype.load = function () {
  69507. this.waitingTasksCount = this.tasks.length;
  69508. if (this.waitingTasksCount === 0) {
  69509. if (this.onFinish) {
  69510. this.onFinish(this.tasks);
  69511. }
  69512. return this;
  69513. }
  69514. if (this.useDefaultLoadingScreen) {
  69515. this._scene.getEngine().displayLoadingUI();
  69516. }
  69517. for (var index = 0; index < this.tasks.length; index++) {
  69518. var task = this.tasks[index];
  69519. this._runTask(task);
  69520. }
  69521. return this;
  69522. };
  69523. return AssetsManager;
  69524. }());
  69525. BABYLON.AssetsManager = AssetsManager;
  69526. })(BABYLON || (BABYLON = {}));
  69527. //# sourceMappingURL=babylon.assetsManager.js.map
  69528. var BABYLON;
  69529. (function (BABYLON) {
  69530. var MapTexture = (function (_super) {
  69531. __extends(MapTexture, _super);
  69532. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  69533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69534. if (useMipMap === void 0) { useMipMap = false; }
  69535. if (margin === void 0) { margin = 0; }
  69536. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  69537. _this.name = name;
  69538. _this._size = size;
  69539. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69540. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69541. // Create the rectPackMap that will allocate portion of the texture
  69542. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  69543. // Create the texture that will store the content
  69544. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  69545. return _this;
  69546. }
  69547. /**
  69548. * Allocate a rectangle of a given size in the texture map
  69549. * @param size the size of the rectangle to allocation
  69550. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  69551. */
  69552. MapTexture.prototype.allocateRect = function (size) {
  69553. return this._rectPackingMap.addRect(size);
  69554. };
  69555. /**
  69556. * Free a given rectangle from the texture map
  69557. * @param rectInfo the instance corresponding to the rect to free.
  69558. */
  69559. MapTexture.prototype.freeRect = function (rectInfo) {
  69560. if (rectInfo) {
  69561. rectInfo.freeContent();
  69562. }
  69563. };
  69564. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  69565. /**
  69566. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  69567. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  69568. * @returns {}
  69569. */
  69570. get: function () {
  69571. return this._rectPackingMap.freeSpace;
  69572. },
  69573. enumerable: true,
  69574. configurable: true
  69575. });
  69576. /**
  69577. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  69578. * 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.
  69579. * Don't forget to call unbindTexture when you're done rendering
  69580. * @param rect the zone to render to
  69581. * @param clear true to clear the portion's color/depth data
  69582. */
  69583. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  69584. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  69585. };
  69586. /**
  69587. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  69588. * 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.
  69589. * Don't forget to call unbindTexture when you're done rendering
  69590. * @param pos the position into the texture
  69591. * @param size the portion to fit the clip space to
  69592. * @param clear true to clear the portion's color/depth data
  69593. */
  69594. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  69595. var engine = this.getScene().getEngine();
  69596. engine.bindFramebuffer(this._texture);
  69597. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  69598. if (clear) {
  69599. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  69600. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  69601. }
  69602. };
  69603. /**
  69604. * Unbind the texture map from the rendering engine.
  69605. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  69606. * @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.
  69607. */
  69608. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  69609. // Dump ?
  69610. if (dumpForDebug) {
  69611. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  69612. }
  69613. var engine = this.getScene().getEngine();
  69614. if (this._replacedViewport) {
  69615. engine.setViewport(this._replacedViewport);
  69616. this._replacedViewport = null;
  69617. }
  69618. engine.unBindFramebuffer(this._texture);
  69619. };
  69620. Object.defineProperty(MapTexture.prototype, "canRescale", {
  69621. get: function () {
  69622. return false;
  69623. },
  69624. enumerable: true,
  69625. configurable: true
  69626. });
  69627. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  69628. // Anyway, there's not much point to use this method for this kind of texture I guess
  69629. MapTexture.prototype.clone = function () {
  69630. return null;
  69631. };
  69632. return MapTexture;
  69633. }(BABYLON.Texture));
  69634. BABYLON.MapTexture = MapTexture;
  69635. })(BABYLON || (BABYLON = {}));
  69636. //# sourceMappingURL=babylon.mapTexture.js.map
  69637. var BABYLON;
  69638. (function (BABYLON) {
  69639. /**
  69640. * This class describe a rectangle that were added to the map.
  69641. * You have access to its coordinates either in pixel or normalized (UV)
  69642. */
  69643. var PackedRect = (function () {
  69644. function PackedRect(root, parent, pos, size) {
  69645. this._pos = pos;
  69646. this._size = size;
  69647. this._root = root;
  69648. this._parent = parent;
  69649. this._contentSize = null;
  69650. this._bottomNode = null;
  69651. this._leftNode = null;
  69652. this._initialSize = null;
  69653. this._rightNode = null;
  69654. }
  69655. Object.defineProperty(PackedRect.prototype, "pos", {
  69656. /**
  69657. * @returns the position of this node into the map
  69658. */
  69659. get: function () {
  69660. return this._pos;
  69661. },
  69662. enumerable: true,
  69663. configurable: true
  69664. });
  69665. Object.defineProperty(PackedRect.prototype, "contentSize", {
  69666. /**
  69667. * @returns the size of the rectangle this node handles
  69668. */
  69669. get: function () {
  69670. return this._contentSize;
  69671. },
  69672. enumerable: true,
  69673. configurable: true
  69674. });
  69675. /**
  69676. * Retrieve the inner position (considering the margin) and stores it into the res object
  69677. * @param res must be a valid Vector2 that will contain the inner position after this call
  69678. */
  69679. PackedRect.prototype.getInnerPosToRef = function (res) {
  69680. var m = this._root._margin;
  69681. res.x = this._pos.x + m;
  69682. res.y = this._pos.y + m;
  69683. };
  69684. /**
  69685. * Retrieve the inner size (considering the margin) and stores it into the res object
  69686. * @param res must be a valid Size that will contain the inner size after this call
  69687. */
  69688. PackedRect.prototype.getInnerSizeToRef = function (res) {
  69689. var m = this._root._margin;
  69690. res.width = this._contentSize.width - (m * 2);
  69691. res.height = this._contentSize.height - (m * 2);
  69692. };
  69693. Object.defineProperty(PackedRect.prototype, "UVs", {
  69694. /**
  69695. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  69696. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  69697. */
  69698. get: function () {
  69699. if (!this._contentSize) {
  69700. throw new Error("Can't compute UVs for this object because it's nor allocated");
  69701. }
  69702. return this.getUVsForCustomSize(this._contentSize);
  69703. },
  69704. enumerable: true,
  69705. configurable: true
  69706. });
  69707. /**
  69708. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  69709. * and then using only a part of the PackRect.
  69710. * This method will return the UVs for this part by given the custom size of what you really use
  69711. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  69712. */
  69713. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  69714. var mainWidth = this._root._size.width;
  69715. var mainHeight = this._root._size.height;
  69716. var margin = this._root._margin;
  69717. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  69718. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  69719. var uvs = new Array();
  69720. uvs.push(topLeft);
  69721. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  69722. uvs.push(rightBottom);
  69723. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  69724. return uvs;
  69725. };
  69726. /**
  69727. * Free this rectangle from the map.
  69728. * Call this method when you no longer need the rectangle to be in the map.
  69729. */
  69730. PackedRect.prototype.freeContent = function () {
  69731. if (!this.contentSize) {
  69732. return;
  69733. }
  69734. this._contentSize = null;
  69735. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  69736. this.attemptDefrag();
  69737. };
  69738. Object.defineProperty(PackedRect.prototype, "isUsed", {
  69739. get: function () {
  69740. return this._contentSize != null || this._leftNode != null;
  69741. },
  69742. enumerable: true,
  69743. configurable: true
  69744. });
  69745. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  69746. var node = this.findNode(contentSize);
  69747. // Not enough space...
  69748. if (!node) {
  69749. return null;
  69750. }
  69751. node.splitNode(contentSize);
  69752. return node;
  69753. };
  69754. PackedRect.prototype.findNode = function (size) {
  69755. var resNode = null;
  69756. var margin = this._root._margin * 2;
  69757. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  69758. if (this.isUsed) {
  69759. if (this._leftNode) {
  69760. resNode = this._leftNode.findNode(size);
  69761. }
  69762. if (!resNode && this._rightNode) {
  69763. resNode = this._rightNode.findNode(size);
  69764. }
  69765. if (!resNode && this._bottomNode) {
  69766. resNode = this._bottomNode.findNode(size);
  69767. }
  69768. }
  69769. else if (this._initialSize) {
  69770. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  69771. resNode = this;
  69772. }
  69773. else {
  69774. return null;
  69775. }
  69776. }
  69777. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  69778. resNode = this;
  69779. }
  69780. return resNode;
  69781. };
  69782. PackedRect.prototype.splitNode = function (contentSize) {
  69783. var cs = PackedRect.TpsSize;
  69784. var margin = this._root._margin * 2;
  69785. cs.copyFrom(contentSize);
  69786. cs.width += margin;
  69787. cs.height += margin;
  69788. // 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)
  69789. if (!this._contentSize && this._initialSize) {
  69790. this._contentSize = cs.clone();
  69791. 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));
  69792. return this._leftNode.splitNode(contentSize);
  69793. }
  69794. else {
  69795. this._contentSize = cs.clone();
  69796. this._initialSize = cs.clone();
  69797. if (cs.width !== this._size.width) {
  69798. 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));
  69799. }
  69800. if (cs.height !== this._size.height) {
  69801. 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));
  69802. }
  69803. return this;
  69804. }
  69805. };
  69806. PackedRect.prototype.attemptDefrag = function () {
  69807. if (!this.isUsed && this.isRecursiveFree) {
  69808. this.clearNode();
  69809. if (this._parent) {
  69810. this._parent.attemptDefrag();
  69811. }
  69812. }
  69813. };
  69814. PackedRect.prototype.clearNode = function () {
  69815. this._initialSize = null;
  69816. this._rightNode = null;
  69817. this._bottomNode = null;
  69818. };
  69819. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  69820. get: function () {
  69821. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  69822. },
  69823. enumerable: true,
  69824. configurable: true
  69825. });
  69826. PackedRect.prototype.evalFreeSize = function (size) {
  69827. var levelSize = 0;
  69828. if (!this.isUsed) {
  69829. var margin = this._root._margin;
  69830. var is = this._initialSize;
  69831. if (is) {
  69832. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  69833. }
  69834. else {
  69835. var size_1 = this._size;
  69836. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  69837. }
  69838. }
  69839. if (this._rightNode) {
  69840. levelSize += this._rightNode.evalFreeSize(0);
  69841. }
  69842. if (this._bottomNode) {
  69843. levelSize += this._bottomNode.evalFreeSize(0);
  69844. }
  69845. return levelSize + size;
  69846. };
  69847. PackedRect.TpsSize = BABYLON.Size.Zero();
  69848. return PackedRect;
  69849. }());
  69850. BABYLON.PackedRect = PackedRect;
  69851. /**
  69852. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  69853. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  69854. * 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.
  69855. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  69856. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  69857. */
  69858. var RectPackingMap = (function (_super) {
  69859. __extends(RectPackingMap, _super);
  69860. /**
  69861. * Create an instance of the object with a dimension using the given size
  69862. * @param size The dimension of the rectangle that will contain all the sub ones.
  69863. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  69864. */
  69865. function RectPackingMap(size, margin) {
  69866. if (margin === void 0) { margin = 0; }
  69867. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  69868. _this._margin = margin;
  69869. _this._root = _this;
  69870. return _this;
  69871. }
  69872. /**
  69873. * Add a rectangle, finding the best location to store it into the map
  69874. * @param size the dimension of the rectangle to store
  69875. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  69876. */
  69877. RectPackingMap.prototype.addRect = function (size) {
  69878. var node = this.findAndSplitNode(size);
  69879. return node;
  69880. };
  69881. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  69882. /**
  69883. * Return the current space free normalized between [0;1]
  69884. * @returns {}
  69885. */
  69886. get: function () {
  69887. var freeSize = 0;
  69888. freeSize = this.evalFreeSize(freeSize);
  69889. return freeSize / (this._size.width * this._size.height);
  69890. },
  69891. enumerable: true,
  69892. configurable: true
  69893. });
  69894. return RectPackingMap;
  69895. }(PackedRect));
  69896. BABYLON.RectPackingMap = RectPackingMap;
  69897. })(BABYLON || (BABYLON = {}));
  69898. //# sourceMappingURL=babylon.rectPackingMap.js.map
  69899. var BABYLON;
  69900. (function (BABYLON) {
  69901. /**
  69902. * This groups together the common properties used for image processing either in direct forward pass
  69903. * or through post processing effect depending on the use of the image processing pipeline in your scene
  69904. * or not.
  69905. */
  69906. var ImageProcessingConfiguration = (function () {
  69907. function ImageProcessingConfiguration() {
  69908. /**
  69909. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  69910. */
  69911. this.colorCurves = new BABYLON.ColorCurves();
  69912. this._colorCurvesEnabled = false;
  69913. this._colorGradingEnabled = false;
  69914. this._colorGradingWithGreenDepth = false;
  69915. this._colorGradingBGR = false;
  69916. this._exposure = 1.0;
  69917. this._toneMappingEnabled = false;
  69918. this._contrast = 1.0;
  69919. /**
  69920. * Vignette stretch size.
  69921. */
  69922. this.vignetteStretch = 0;
  69923. /**
  69924. * Vignette centre X Offset.
  69925. */
  69926. this.vignetteCentreX = 0;
  69927. /**
  69928. * Vignette centre Y Offset.
  69929. */
  69930. this.vignetteCentreY = 0;
  69931. /**
  69932. * Vignette weight or intensity of the vignette effect.
  69933. */
  69934. this.vignetteWeight = 1.5;
  69935. /**
  69936. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69937. * if vignetteEnabled is set to true.
  69938. */
  69939. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  69940. /**
  69941. * Camera field of view used by the Vignette effect.
  69942. */
  69943. this.vignetteCameraFov = 0.5;
  69944. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  69945. this._vignetteEnabled = false;
  69946. this._applyByPostProcess = false;
  69947. /**
  69948. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  69949. * @type {BABYLON.Observable}
  69950. */
  69951. this.onUpdateParameters = new BABYLON.Observable();
  69952. }
  69953. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  69954. /**
  69955. * Gets wether the color curves effect is enabled.
  69956. */
  69957. get: function () {
  69958. return this._colorCurvesEnabled;
  69959. },
  69960. /**
  69961. * Sets wether the color curves effect is enabled.
  69962. */
  69963. set: function (value) {
  69964. if (this._colorCurvesEnabled === value) {
  69965. return;
  69966. }
  69967. this._colorCurvesEnabled = value;
  69968. this._updateParameters();
  69969. },
  69970. enumerable: true,
  69971. configurable: true
  69972. });
  69973. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  69974. /**
  69975. * Gets wether the color grading effect is enabled.
  69976. */
  69977. get: function () {
  69978. return this._colorGradingEnabled;
  69979. },
  69980. /**
  69981. * Sets wether the color grading effect is enabled.
  69982. */
  69983. set: function (value) {
  69984. if (this._colorGradingEnabled === value) {
  69985. return;
  69986. }
  69987. this._colorGradingEnabled = value;
  69988. this._updateParameters();
  69989. },
  69990. enumerable: true,
  69991. configurable: true
  69992. });
  69993. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  69994. /**
  69995. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  69996. */
  69997. get: function () {
  69998. return this._colorGradingWithGreenDepth;
  69999. },
  70000. /**
  70001. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  70002. */
  70003. set: function (value) {
  70004. if (this._colorGradingWithGreenDepth === value) {
  70005. return;
  70006. }
  70007. this._colorGradingWithGreenDepth = value;
  70008. this._updateParameters();
  70009. },
  70010. enumerable: true,
  70011. configurable: true
  70012. });
  70013. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  70014. /**
  70015. * Gets wether the color grading texture contains BGR values.
  70016. */
  70017. get: function () {
  70018. return this._colorGradingBGR;
  70019. },
  70020. /**
  70021. * Sets wether the color grading texture contains BGR values.
  70022. */
  70023. set: function (value) {
  70024. if (this._colorGradingBGR === value) {
  70025. return;
  70026. }
  70027. this._colorGradingBGR = value;
  70028. this._updateParameters();
  70029. },
  70030. enumerable: true,
  70031. configurable: true
  70032. });
  70033. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  70034. /**
  70035. * Gets the Exposure used in the effect.
  70036. */
  70037. get: function () {
  70038. return this._exposure;
  70039. },
  70040. /**
  70041. * Sets the Exposure used in the effect.
  70042. */
  70043. set: function (value) {
  70044. if (this._exposure === value) {
  70045. return;
  70046. }
  70047. this._exposure = value;
  70048. this._updateParameters();
  70049. },
  70050. enumerable: true,
  70051. configurable: true
  70052. });
  70053. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  70054. /**
  70055. * Gets wether the tone mapping effect is enabled.
  70056. */
  70057. get: function () {
  70058. return this._toneMappingEnabled;
  70059. },
  70060. /**
  70061. * Sets wether the tone mapping effect is enabled.
  70062. */
  70063. set: function (value) {
  70064. if (this._toneMappingEnabled === value) {
  70065. return;
  70066. }
  70067. this._toneMappingEnabled = value;
  70068. this._updateParameters();
  70069. },
  70070. enumerable: true,
  70071. configurable: true
  70072. });
  70073. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  70074. /**
  70075. * Gets the contrast used in the effect.
  70076. */
  70077. get: function () {
  70078. return this._contrast;
  70079. },
  70080. /**
  70081. * Sets the contrast used in the effect.
  70082. */
  70083. set: function (value) {
  70084. if (this._contrast === value) {
  70085. return;
  70086. }
  70087. this._contrast = value;
  70088. this._updateParameters();
  70089. },
  70090. enumerable: true,
  70091. configurable: true
  70092. });
  70093. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  70094. /**
  70095. * Gets the vignette blend mode allowing different kind of effect.
  70096. */
  70097. get: function () {
  70098. return this._vignetteBlendMode;
  70099. },
  70100. /**
  70101. * Sets the vignette blend mode allowing different kind of effect.
  70102. */
  70103. set: function (value) {
  70104. if (this._vignetteBlendMode === value) {
  70105. return;
  70106. }
  70107. this._vignetteBlendMode = value;
  70108. this._updateParameters();
  70109. },
  70110. enumerable: true,
  70111. configurable: true
  70112. });
  70113. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  70114. /**
  70115. * Gets wether the vignette effect is enabled.
  70116. */
  70117. get: function () {
  70118. return this._vignetteEnabled;
  70119. },
  70120. /**
  70121. * Sets wether the vignette effect is enabled.
  70122. */
  70123. set: function (value) {
  70124. if (this._vignetteEnabled === value) {
  70125. return;
  70126. }
  70127. this._vignetteEnabled = value;
  70128. this._updateParameters();
  70129. },
  70130. enumerable: true,
  70131. configurable: true
  70132. });
  70133. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  70134. /**
  70135. * Gets wether the image processing is applied through a post process or not.
  70136. */
  70137. get: function () {
  70138. return this._applyByPostProcess;
  70139. },
  70140. /**
  70141. * Sets wether the image processing is applied through a post process or not.
  70142. */
  70143. set: function (value) {
  70144. if (this._applyByPostProcess === value) {
  70145. return;
  70146. }
  70147. this._applyByPostProcess = value;
  70148. this._updateParameters();
  70149. },
  70150. enumerable: true,
  70151. configurable: true
  70152. });
  70153. /**
  70154. * Method called each time the image processing information changes requires to recompile the effect.
  70155. */
  70156. ImageProcessingConfiguration.prototype._updateParameters = function () {
  70157. this.onUpdateParameters.notifyObservers(this);
  70158. };
  70159. ImageProcessingConfiguration.prototype.getClassName = function () {
  70160. return "ImageProcessingConfiguration";
  70161. };
  70162. /**
  70163. * Prepare the list of uniforms associated with the Image Processing effects.
  70164. * @param uniformsList The list of uniforms used in the effect
  70165. * @param defines the list of defines currently in use
  70166. */
  70167. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  70168. if (defines.EXPOSURE) {
  70169. uniforms.push("exposureLinear");
  70170. }
  70171. if (defines.CONTRAST) {
  70172. uniforms.push("contrast");
  70173. }
  70174. if (defines.COLORGRADING) {
  70175. uniforms.push("colorTransformSettings");
  70176. }
  70177. if (defines.VIGNETTE) {
  70178. uniforms.push("vInverseScreenSize");
  70179. uniforms.push("vignetteSettings1");
  70180. uniforms.push("vignetteSettings2");
  70181. }
  70182. if (defines.COLORCURVES) {
  70183. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  70184. }
  70185. };
  70186. /**
  70187. * Prepare the list of samplers associated with the Image Processing effects.
  70188. * @param uniformsList The list of uniforms used in the effect
  70189. * @param defines the list of defines currently in use
  70190. */
  70191. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  70192. if (defines.COLORGRADING) {
  70193. samplersList.push("txColorTransform");
  70194. }
  70195. };
  70196. /**
  70197. * Prepare the list of defines associated to the shader.
  70198. * @param defines the list of defines to complete
  70199. */
  70200. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  70201. defines.VIGNETTE = this.vignetteEnabled;
  70202. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  70203. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  70204. defines.TONEMAPPING = this.toneMappingEnabled;
  70205. defines.CONTRAST = (this.contrast !== 1.0);
  70206. defines.EXPOSURE = (this.exposure !== 1.0);
  70207. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  70208. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  70209. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  70210. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  70211. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70212. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  70213. };
  70214. /**
  70215. * Returns true if all the image processing information are ready.
  70216. */
  70217. ImageProcessingConfiguration.prototype.isReady = function () {
  70218. // Color Grading texure can not be none blocking.
  70219. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  70220. };
  70221. /**
  70222. * Binds the image processing to the shader.
  70223. * @param effect The effect to bind to
  70224. */
  70225. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  70226. if (aspectRatio === void 0) { aspectRatio = 1; }
  70227. // Color Curves
  70228. if (this._colorCurvesEnabled) {
  70229. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  70230. }
  70231. // Vignette
  70232. if (this._vignetteEnabled) {
  70233. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  70234. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  70235. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  70236. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  70237. var vignetteScaleX = vignetteScaleY * aspectRatio;
  70238. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  70239. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  70240. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  70241. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  70242. var vignettePower = -2.0 * this.vignetteWeight;
  70243. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  70244. }
  70245. // Exposure
  70246. effect.setFloat("exposureLinear", this.exposure);
  70247. // Contrast
  70248. effect.setFloat("contrast", this.contrast);
  70249. // Color transform settings
  70250. if (this.colorGradingTexture) {
  70251. effect.setTexture("txColorTransform", this.colorGradingTexture);
  70252. var textureSize = this.colorGradingTexture.getSize().height;
  70253. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  70254. 0.5 / textureSize, // textureOffset
  70255. textureSize, // textureSize
  70256. this.colorGradingTexture.level // weight
  70257. );
  70258. }
  70259. };
  70260. /**
  70261. * Clones the current image processing instance.
  70262. * @return The cloned image processing
  70263. */
  70264. ImageProcessingConfiguration.prototype.clone = function () {
  70265. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  70266. };
  70267. /**
  70268. * Serializes the current image processing instance to a json representation.
  70269. * @return a JSON representation
  70270. */
  70271. ImageProcessingConfiguration.prototype.serialize = function () {
  70272. return BABYLON.SerializationHelper.Serialize(this);
  70273. };
  70274. /**
  70275. * Parses the image processing from a json representation.
  70276. * @param source the JSON source to parse
  70277. * @return The parsed image processing
  70278. */
  70279. ImageProcessingConfiguration.Parse = function (source) {
  70280. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  70281. };
  70282. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  70283. /**
  70284. * Used to apply the vignette as a mix with the pixel color.
  70285. */
  70286. get: function () {
  70287. return this._VIGNETTEMODE_MULTIPLY;
  70288. },
  70289. enumerable: true,
  70290. configurable: true
  70291. });
  70292. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  70293. /**
  70294. * Used to apply the vignette as a replacement of the pixel color.
  70295. */
  70296. get: function () {
  70297. return this._VIGNETTEMODE_OPAQUE;
  70298. },
  70299. enumerable: true,
  70300. configurable: true
  70301. });
  70302. // Static constants associated to the image processing.
  70303. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  70304. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  70305. __decorate([
  70306. BABYLON.serializeAsColorCurves()
  70307. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  70308. __decorate([
  70309. BABYLON.serialize()
  70310. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  70311. __decorate([
  70312. BABYLON.serializeAsTexture()
  70313. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  70314. __decorate([
  70315. BABYLON.serialize()
  70316. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  70317. __decorate([
  70318. BABYLON.serialize()
  70319. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  70320. __decorate([
  70321. BABYLON.serialize()
  70322. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  70323. __decorate([
  70324. BABYLON.serialize()
  70325. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  70326. __decorate([
  70327. BABYLON.serialize()
  70328. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  70329. __decorate([
  70330. BABYLON.serialize()
  70331. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  70332. __decorate([
  70333. BABYLON.serialize()
  70334. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  70335. __decorate([
  70336. BABYLON.serialize()
  70337. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  70338. __decorate([
  70339. BABYLON.serialize()
  70340. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  70341. __decorate([
  70342. BABYLON.serialize()
  70343. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  70344. __decorate([
  70345. BABYLON.serializeAsColor4()
  70346. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  70347. __decorate([
  70348. BABYLON.serialize()
  70349. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  70350. __decorate([
  70351. BABYLON.serialize()
  70352. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  70353. __decorate([
  70354. BABYLON.serialize()
  70355. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  70356. __decorate([
  70357. BABYLON.serialize()
  70358. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  70359. return ImageProcessingConfiguration;
  70360. }());
  70361. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  70362. })(BABYLON || (BABYLON = {}));
  70363. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  70364. var BABYLON;
  70365. (function (BABYLON) {
  70366. var serializedGeometries = [];
  70367. var serializeGeometry = function (geometry, serializationGeometries) {
  70368. if (serializedGeometries[geometry.id]) {
  70369. return;
  70370. }
  70371. if (geometry.doNotSerialize) {
  70372. return;
  70373. }
  70374. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  70375. serializationGeometries.boxes.push(geometry.serialize());
  70376. }
  70377. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  70378. serializationGeometries.spheres.push(geometry.serialize());
  70379. }
  70380. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  70381. serializationGeometries.cylinders.push(geometry.serialize());
  70382. }
  70383. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  70384. serializationGeometries.toruses.push(geometry.serialize());
  70385. }
  70386. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  70387. serializationGeometries.grounds.push(geometry.serialize());
  70388. }
  70389. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  70390. serializationGeometries.planes.push(geometry.serialize());
  70391. }
  70392. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  70393. serializationGeometries.torusKnots.push(geometry.serialize());
  70394. }
  70395. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  70396. throw new Error("Unknown primitive type");
  70397. }
  70398. else {
  70399. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  70400. }
  70401. serializedGeometries[geometry.id] = true;
  70402. };
  70403. var serializeMesh = function (mesh, serializationScene) {
  70404. var serializationObject = {};
  70405. // Geometry
  70406. var geometry = mesh._geometry;
  70407. if (geometry) {
  70408. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  70409. // 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
  70410. serializeGeometry(geometry, serializationScene.geometries);
  70411. }
  70412. }
  70413. // Custom
  70414. if (mesh.serialize) {
  70415. mesh.serialize(serializationObject);
  70416. }
  70417. return serializationObject;
  70418. };
  70419. var finalizeSingleMesh = function (mesh, serializationObject) {
  70420. //only works if the mesh is already loaded
  70421. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70422. //serialize material
  70423. if (mesh.material) {
  70424. if (mesh.material instanceof BABYLON.StandardMaterial) {
  70425. serializationObject.materials = serializationObject.materials || [];
  70426. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70427. serializationObject.materials.push(mesh.material.serialize());
  70428. }
  70429. }
  70430. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  70431. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  70432. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70433. serializationObject.multiMaterials.push(mesh.material.serialize());
  70434. }
  70435. }
  70436. }
  70437. //serialize geometry
  70438. var geometry = mesh._geometry;
  70439. if (geometry) {
  70440. if (!serializationObject.geometries) {
  70441. serializationObject.geometries = {};
  70442. serializationObject.geometries.boxes = [];
  70443. serializationObject.geometries.spheres = [];
  70444. serializationObject.geometries.cylinders = [];
  70445. serializationObject.geometries.toruses = [];
  70446. serializationObject.geometries.grounds = [];
  70447. serializationObject.geometries.planes = [];
  70448. serializationObject.geometries.torusKnots = [];
  70449. serializationObject.geometries.vertexData = [];
  70450. }
  70451. serializeGeometry(geometry, serializationObject.geometries);
  70452. }
  70453. // Skeletons
  70454. if (mesh.skeleton) {
  70455. serializationObject.skeletons = serializationObject.skeletons || [];
  70456. serializationObject.skeletons.push(mesh.skeleton.serialize());
  70457. }
  70458. //serialize the actual mesh
  70459. serializationObject.meshes = serializationObject.meshes || [];
  70460. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70461. }
  70462. };
  70463. var SceneSerializer = (function () {
  70464. function SceneSerializer() {
  70465. }
  70466. SceneSerializer.ClearCache = function () {
  70467. serializedGeometries = [];
  70468. };
  70469. SceneSerializer.Serialize = function (scene) {
  70470. var serializationObject = {};
  70471. SceneSerializer.ClearCache();
  70472. // Scene
  70473. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  70474. serializationObject.autoClear = scene.autoClear;
  70475. serializationObject.clearColor = scene.clearColor.asArray();
  70476. serializationObject.ambientColor = scene.ambientColor.asArray();
  70477. serializationObject.gravity = scene.gravity.asArray();
  70478. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  70479. serializationObject.workerCollisions = scene.workerCollisions;
  70480. // Fog
  70481. if (scene.fogMode && scene.fogMode !== 0) {
  70482. serializationObject.fogMode = scene.fogMode;
  70483. serializationObject.fogColor = scene.fogColor.asArray();
  70484. serializationObject.fogStart = scene.fogStart;
  70485. serializationObject.fogEnd = scene.fogEnd;
  70486. serializationObject.fogDensity = scene.fogDensity;
  70487. }
  70488. //Physics
  70489. if (scene.isPhysicsEnabled()) {
  70490. serializationObject.physicsEnabled = true;
  70491. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  70492. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  70493. }
  70494. // Metadata
  70495. if (scene.metadata) {
  70496. serializationObject.metadata = scene.metadata;
  70497. }
  70498. // Morph targets
  70499. serializationObject.morphTargetManagers = [];
  70500. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  70501. var abstractMesh = _a[_i];
  70502. var manager = abstractMesh.morphTargetManager;
  70503. if (manager) {
  70504. serializationObject.morphTargetManagers.push(manager.serialize());
  70505. }
  70506. }
  70507. // Lights
  70508. serializationObject.lights = [];
  70509. var index;
  70510. var light;
  70511. for (index = 0; index < scene.lights.length; index++) {
  70512. light = scene.lights[index];
  70513. if (!light.doNotSerialize) {
  70514. serializationObject.lights.push(light.serialize());
  70515. }
  70516. }
  70517. // Cameras
  70518. serializationObject.cameras = [];
  70519. for (index = 0; index < scene.cameras.length; index++) {
  70520. var camera = scene.cameras[index];
  70521. if (!camera.doNotSerialize) {
  70522. serializationObject.cameras.push(camera.serialize());
  70523. }
  70524. }
  70525. if (scene.activeCamera) {
  70526. serializationObject.activeCameraID = scene.activeCamera.id;
  70527. }
  70528. // Animations
  70529. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  70530. // Materials
  70531. serializationObject.materials = [];
  70532. serializationObject.multiMaterials = [];
  70533. var material;
  70534. for (index = 0; index < scene.materials.length; index++) {
  70535. material = scene.materials[index];
  70536. if (!material.doNotSerialize) {
  70537. serializationObject.materials.push(material.serialize());
  70538. }
  70539. }
  70540. // MultiMaterials
  70541. serializationObject.multiMaterials = [];
  70542. for (index = 0; index < scene.multiMaterials.length; index++) {
  70543. var multiMaterial = scene.multiMaterials[index];
  70544. serializationObject.multiMaterials.push(multiMaterial.serialize());
  70545. }
  70546. // Skeletons
  70547. serializationObject.skeletons = [];
  70548. for (index = 0; index < scene.skeletons.length; index++) {
  70549. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  70550. }
  70551. // Geometries
  70552. serializationObject.geometries = {};
  70553. serializationObject.geometries.boxes = [];
  70554. serializationObject.geometries.spheres = [];
  70555. serializationObject.geometries.cylinders = [];
  70556. serializationObject.geometries.toruses = [];
  70557. serializationObject.geometries.grounds = [];
  70558. serializationObject.geometries.planes = [];
  70559. serializationObject.geometries.torusKnots = [];
  70560. serializationObject.geometries.vertexData = [];
  70561. serializedGeometries = [];
  70562. var geometries = scene.getGeometries();
  70563. for (index = 0; index < geometries.length; index++) {
  70564. var geometry = geometries[index];
  70565. if (geometry.isReady()) {
  70566. serializeGeometry(geometry, serializationObject.geometries);
  70567. }
  70568. }
  70569. // Meshes
  70570. serializationObject.meshes = [];
  70571. for (index = 0; index < scene.meshes.length; index++) {
  70572. var abstractMesh = scene.meshes[index];
  70573. if (abstractMesh instanceof BABYLON.Mesh) {
  70574. var mesh = abstractMesh;
  70575. if (!mesh.doNotSerialize) {
  70576. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70577. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70578. }
  70579. }
  70580. }
  70581. }
  70582. // Particles Systems
  70583. serializationObject.particleSystems = [];
  70584. for (index = 0; index < scene.particleSystems.length; index++) {
  70585. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  70586. }
  70587. // Lens flares
  70588. serializationObject.lensFlareSystems = [];
  70589. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  70590. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  70591. }
  70592. // Shadows
  70593. serializationObject.shadowGenerators = [];
  70594. for (index = 0; index < scene.lights.length; index++) {
  70595. light = scene.lights[index];
  70596. var shadowGenerator = light.getShadowGenerator();
  70597. if (shadowGenerator) {
  70598. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70599. }
  70600. }
  70601. // Action Manager
  70602. if (scene.actionManager) {
  70603. serializationObject.actions = scene.actionManager.serialize("scene");
  70604. }
  70605. // Audio
  70606. serializationObject.sounds = [];
  70607. for (index = 0; index < scene.soundTracks.length; index++) {
  70608. var soundtrack = scene.soundTracks[index];
  70609. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70610. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70611. }
  70612. }
  70613. return serializationObject;
  70614. };
  70615. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  70616. if (withParents === void 0) { withParents = false; }
  70617. if (withChildren === void 0) { withChildren = false; }
  70618. var serializationObject = {};
  70619. SceneSerializer.ClearCache();
  70620. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  70621. if (withParents || withChildren) {
  70622. //deliberate for loop! not for each, appended should be processed as well.
  70623. for (var i = 0; i < toSerialize.length; ++i) {
  70624. if (withChildren) {
  70625. toSerialize[i].getDescendants().forEach(function (node) {
  70626. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  70627. toSerialize.push(node);
  70628. }
  70629. });
  70630. }
  70631. //make sure the array doesn't contain the object already
  70632. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  70633. toSerialize.push(toSerialize[i].parent);
  70634. }
  70635. }
  70636. }
  70637. toSerialize.forEach(function (mesh) {
  70638. finalizeSingleMesh(mesh, serializationObject);
  70639. });
  70640. return serializationObject;
  70641. };
  70642. return SceneSerializer;
  70643. }());
  70644. BABYLON.SceneSerializer = SceneSerializer;
  70645. })(BABYLON || (BABYLON = {}));
  70646. //# sourceMappingURL=babylon.sceneSerializer.js.map
  70647. var BABYLON;
  70648. (function (BABYLON) {
  70649. var ReflectionProbe = (function () {
  70650. function ReflectionProbe(name, size, scene, generateMipMaps) {
  70651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70652. var _this = this;
  70653. this.name = name;
  70654. this._viewMatrix = BABYLON.Matrix.Identity();
  70655. this._target = BABYLON.Vector3.Zero();
  70656. this._add = BABYLON.Vector3.Zero();
  70657. this.invertYAxis = false;
  70658. this.position = BABYLON.Vector3.Zero();
  70659. this._scene = scene;
  70660. this._scene.reflectionProbes.push(this);
  70661. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  70662. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  70663. switch (faceIndex) {
  70664. case 0:
  70665. _this._add.copyFromFloats(1, 0, 0);
  70666. break;
  70667. case 1:
  70668. _this._add.copyFromFloats(-1, 0, 0);
  70669. break;
  70670. case 2:
  70671. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  70672. break;
  70673. case 3:
  70674. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  70675. break;
  70676. case 4:
  70677. _this._add.copyFromFloats(0, 0, 1);
  70678. break;
  70679. case 5:
  70680. _this._add.copyFromFloats(0, 0, -1);
  70681. break;
  70682. }
  70683. if (_this._attachedMesh) {
  70684. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  70685. }
  70686. _this.position.addToRef(_this._add, _this._target);
  70687. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  70688. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  70689. });
  70690. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  70691. scene.updateTransformMatrix(true);
  70692. });
  70693. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70694. }
  70695. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  70696. get: function () {
  70697. return this._renderTargetTexture.samples;
  70698. },
  70699. set: function (value) {
  70700. this._renderTargetTexture.samples = value;
  70701. },
  70702. enumerable: true,
  70703. configurable: true
  70704. });
  70705. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  70706. get: function () {
  70707. return this._renderTargetTexture.refreshRate;
  70708. },
  70709. set: function (value) {
  70710. this._renderTargetTexture.refreshRate = value;
  70711. },
  70712. enumerable: true,
  70713. configurable: true
  70714. });
  70715. ReflectionProbe.prototype.getScene = function () {
  70716. return this._scene;
  70717. };
  70718. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  70719. get: function () {
  70720. return this._renderTargetTexture;
  70721. },
  70722. enumerable: true,
  70723. configurable: true
  70724. });
  70725. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  70726. get: function () {
  70727. return this._renderTargetTexture.renderList;
  70728. },
  70729. enumerable: true,
  70730. configurable: true
  70731. });
  70732. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  70733. this._attachedMesh = mesh;
  70734. };
  70735. /**
  70736. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70737. *
  70738. * @param renderingGroupId The rendering group id corresponding to its index
  70739. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70740. */
  70741. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70742. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70743. };
  70744. ReflectionProbe.prototype.dispose = function () {
  70745. var index = this._scene.reflectionProbes.indexOf(this);
  70746. if (index !== -1) {
  70747. // Remove from the scene if found
  70748. this._scene.reflectionProbes.splice(index, 1);
  70749. }
  70750. if (this._renderTargetTexture) {
  70751. this._renderTargetTexture.dispose();
  70752. this._renderTargetTexture = null;
  70753. }
  70754. };
  70755. return ReflectionProbe;
  70756. }());
  70757. BABYLON.ReflectionProbe = ReflectionProbe;
  70758. })(BABYLON || (BABYLON = {}));
  70759. //# sourceMappingURL=babylon.reflectionProbe.js.map
  70760. var BABYLON;
  70761. (function (BABYLON) {
  70762. var Layer = (function () {
  70763. function Layer(name, imgUrl, scene, isBackground, color) {
  70764. this.name = name;
  70765. this.scale = new BABYLON.Vector2(1, 1);
  70766. this.offset = new BABYLON.Vector2(0, 0);
  70767. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  70768. this.layerMask = 0x0FFFFFFF;
  70769. this._vertexBuffers = {};
  70770. // Events
  70771. /**
  70772. * An event triggered when the layer is disposed.
  70773. * @type {BABYLON.Observable}
  70774. */
  70775. this.onDisposeObservable = new BABYLON.Observable();
  70776. /**
  70777. * An event triggered before rendering the scene
  70778. * @type {BABYLON.Observable}
  70779. */
  70780. this.onBeforeRenderObservable = new BABYLON.Observable();
  70781. /**
  70782. * An event triggered after rendering the scene
  70783. * @type {BABYLON.Observable}
  70784. */
  70785. this.onAfterRenderObservable = new BABYLON.Observable();
  70786. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  70787. this.isBackground = isBackground === undefined ? true : isBackground;
  70788. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  70789. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70790. this._scene.layers.push(this);
  70791. var engine = this._scene.getEngine();
  70792. // VBO
  70793. var vertices = [];
  70794. vertices.push(1, 1);
  70795. vertices.push(-1, 1);
  70796. vertices.push(-1, -1);
  70797. vertices.push(1, -1);
  70798. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70799. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70800. this._createIndexBuffer();
  70801. // Effects
  70802. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  70803. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  70804. }
  70805. Object.defineProperty(Layer.prototype, "onDispose", {
  70806. set: function (callback) {
  70807. if (this._onDisposeObserver) {
  70808. this.onDisposeObservable.remove(this._onDisposeObserver);
  70809. }
  70810. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  70811. },
  70812. enumerable: true,
  70813. configurable: true
  70814. });
  70815. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  70816. set: function (callback) {
  70817. if (this._onBeforeRenderObserver) {
  70818. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70819. }
  70820. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70821. },
  70822. enumerable: true,
  70823. configurable: true
  70824. });
  70825. Object.defineProperty(Layer.prototype, "onAfterRender", {
  70826. set: function (callback) {
  70827. if (this._onAfterRenderObserver) {
  70828. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70829. }
  70830. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70831. },
  70832. enumerable: true,
  70833. configurable: true
  70834. });
  70835. Layer.prototype._createIndexBuffer = function () {
  70836. var engine = this._scene.getEngine();
  70837. // Indices
  70838. var indices = [];
  70839. indices.push(0);
  70840. indices.push(1);
  70841. indices.push(2);
  70842. indices.push(0);
  70843. indices.push(2);
  70844. indices.push(3);
  70845. this._indexBuffer = engine.createIndexBuffer(indices);
  70846. };
  70847. Layer.prototype._rebuild = function () {
  70848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  70849. this._createIndexBuffer();
  70850. };
  70851. Layer.prototype.render = function () {
  70852. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  70853. // Check
  70854. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  70855. return;
  70856. var engine = this._scene.getEngine();
  70857. this.onBeforeRenderObservable.notifyObservers(this);
  70858. // Render
  70859. engine.enableEffect(currentEffect);
  70860. engine.setState(false);
  70861. // Texture
  70862. currentEffect.setTexture("textureSampler", this.texture);
  70863. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  70864. // Color
  70865. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  70866. // Scale / offset
  70867. currentEffect.setVector2("offset", this.offset);
  70868. currentEffect.setVector2("scale", this.scale);
  70869. // VBOs
  70870. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  70871. // Draw order
  70872. if (!this.alphaTest) {
  70873. engine.setAlphaMode(this.alphaBlendingMode);
  70874. engine.draw(true, 0, 6);
  70875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70876. }
  70877. else {
  70878. engine.draw(true, 0, 6);
  70879. }
  70880. this.onAfterRenderObservable.notifyObservers(this);
  70881. };
  70882. Layer.prototype.dispose = function () {
  70883. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70884. if (vertexBuffer) {
  70885. vertexBuffer.dispose();
  70886. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70887. }
  70888. if (this._indexBuffer) {
  70889. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70890. this._indexBuffer = null;
  70891. }
  70892. if (this.texture) {
  70893. this.texture.dispose();
  70894. this.texture = null;
  70895. }
  70896. // Remove from scene
  70897. var index = this._scene.layers.indexOf(this);
  70898. this._scene.layers.splice(index, 1);
  70899. // Callback
  70900. this.onDisposeObservable.notifyObservers(this);
  70901. this.onDisposeObservable.clear();
  70902. this.onAfterRenderObservable.clear();
  70903. this.onBeforeRenderObservable.clear();
  70904. };
  70905. return Layer;
  70906. }());
  70907. BABYLON.Layer = Layer;
  70908. })(BABYLON || (BABYLON = {}));
  70909. //# sourceMappingURL=babylon.layer.js.map
  70910. var BABYLON;
  70911. (function (BABYLON) {
  70912. var TextureTools = (function () {
  70913. function TextureTools() {
  70914. }
  70915. /**
  70916. * Uses the GPU to create a copy texture rescaled at a given size
  70917. * @param texture Texture to copy from
  70918. * @param width Desired width
  70919. * @param height Desired height
  70920. * @return Generated texture
  70921. */
  70922. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  70923. if (useBilinearMode === void 0) { useBilinearMode = true; }
  70924. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  70925. var scene = texture.getScene();
  70926. var engine = scene.getEngine();
  70927. rtt.wrapU = texture.wrapU;
  70928. rtt.wrapV = texture.wrapV;
  70929. rtt.uOffset = texture.uOffset;
  70930. rtt.vOffset = texture.vOffset;
  70931. rtt.uScale = texture.uScale;
  70932. rtt.vScale = texture.vScale;
  70933. rtt.uAng = texture.uAng;
  70934. rtt.vAng = texture.vAng;
  70935. rtt.wAng = texture.wAng;
  70936. rtt.coordinatesIndex = texture.coordinatesIndex;
  70937. rtt.level = texture.level;
  70938. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  70939. rtt._texture.isReady = false;
  70940. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70941. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70942. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70943. passPostProcess.getEffect().executeWhenCompiled(function () {
  70944. passPostProcess.onApply = function (effect) {
  70945. effect.setTexture("textureSampler", texture);
  70946. };
  70947. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  70948. engine.unBindFramebuffer(rtt.getInternalTexture());
  70949. rtt.disposeFramebufferObjects();
  70950. passPostProcess.dispose();
  70951. rtt._texture.isReady = true;
  70952. });
  70953. return rtt;
  70954. };
  70955. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  70956. if (!scene._environmentBRDFTexture) {
  70957. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70958. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70959. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70960. scene._environmentBRDFTexture = texture;
  70961. }
  70962. return scene._environmentBRDFTexture;
  70963. };
  70964. 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=";
  70965. return TextureTools;
  70966. }());
  70967. BABYLON.TextureTools = TextureTools;
  70968. })(BABYLON || (BABYLON = {}));
  70969. //# sourceMappingURL=babylon.textureTools.js.map
  70970. var BABYLON;
  70971. (function (BABYLON) {
  70972. var FramingBehavior = (function () {
  70973. function FramingBehavior() {
  70974. this._mode = FramingBehavior.FitFrustumSidesMode;
  70975. this._radiusScale = 1.0;
  70976. this._positionScale = 0.5;
  70977. this._defaultElevation = 0.3;
  70978. this._elevationReturnTime = 1500;
  70979. this._elevationReturnWaitTime = 1000;
  70980. this._zoomStopsAnimation = false;
  70981. this._framingTime = 1500;
  70982. this._isPointerDown = false;
  70983. this._lastFrameTime = null;
  70984. this._lastInteractionTime = -Infinity;
  70985. // Framing control
  70986. this._animatables = new Array();
  70987. this._betaIsAnimating = false;
  70988. this._lastFrameRadius = 0;
  70989. }
  70990. Object.defineProperty(FramingBehavior.prototype, "name", {
  70991. get: function () {
  70992. return "Framing";
  70993. },
  70994. enumerable: true,
  70995. configurable: true
  70996. });
  70997. Object.defineProperty(FramingBehavior.prototype, "mode", {
  70998. /**
  70999. * Gets current mode used by the behavior.
  71000. */
  71001. get: function () {
  71002. return this._mode;
  71003. },
  71004. /**
  71005. * Sets the current mode used by the behavior
  71006. */
  71007. set: function (mode) {
  71008. this._mode = mode;
  71009. },
  71010. enumerable: true,
  71011. configurable: true
  71012. });
  71013. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  71014. /**
  71015. * Gets the scale applied to the radius
  71016. */
  71017. get: function () {
  71018. return this._radiusScale;
  71019. },
  71020. /**
  71021. * Sets the scale applied to the radius (1 by default)
  71022. */
  71023. set: function (radius) {
  71024. this._radiusScale = radius;
  71025. },
  71026. enumerable: true,
  71027. configurable: true
  71028. });
  71029. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  71030. /**
  71031. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71032. */
  71033. get: function () {
  71034. return this._positionScale;
  71035. },
  71036. /**
  71037. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71038. */
  71039. set: function (scale) {
  71040. this._positionScale = scale;
  71041. },
  71042. enumerable: true,
  71043. configurable: true
  71044. });
  71045. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  71046. /**
  71047. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71048. * behaviour is triggered, in radians.
  71049. */
  71050. get: function () {
  71051. return this._defaultElevation;
  71052. },
  71053. /**
  71054. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71055. * behaviour is triggered, in radians.
  71056. */
  71057. set: function (elevation) {
  71058. this._defaultElevation = elevation;
  71059. },
  71060. enumerable: true,
  71061. configurable: true
  71062. });
  71063. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  71064. /**
  71065. * Gets the time (in milliseconds) taken to return to the default beta position.
  71066. * Negative value indicates camera should not return to default.
  71067. */
  71068. get: function () {
  71069. return this._elevationReturnTime;
  71070. },
  71071. /**
  71072. * Sets the time (in milliseconds) taken to return to the default beta position.
  71073. * Negative value indicates camera should not return to default.
  71074. */
  71075. set: function (speed) {
  71076. this._elevationReturnTime = speed;
  71077. },
  71078. enumerable: true,
  71079. configurable: true
  71080. });
  71081. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  71082. /**
  71083. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71084. */
  71085. get: function () {
  71086. return this._elevationReturnWaitTime;
  71087. },
  71088. /**
  71089. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71090. */
  71091. set: function (time) {
  71092. this._elevationReturnWaitTime = time;
  71093. },
  71094. enumerable: true,
  71095. configurable: true
  71096. });
  71097. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  71098. /**
  71099. * Gets the flag that indicates if user zooming should stop animation.
  71100. */
  71101. get: function () {
  71102. return this._zoomStopsAnimation;
  71103. },
  71104. /**
  71105. * Sets the flag that indicates if user zooming should stop animation.
  71106. */
  71107. set: function (flag) {
  71108. this._zoomStopsAnimation = flag;
  71109. },
  71110. enumerable: true,
  71111. configurable: true
  71112. });
  71113. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  71114. /**
  71115. * Gets the transition time when framing the mesh, in milliseconds
  71116. */
  71117. get: function () {
  71118. return this._framingTime;
  71119. },
  71120. /**
  71121. * Sets the transition time when framing the mesh, in milliseconds
  71122. */
  71123. set: function (time) {
  71124. this._framingTime = time;
  71125. },
  71126. enumerable: true,
  71127. configurable: true
  71128. });
  71129. FramingBehavior.prototype.attach = function (camera) {
  71130. var _this = this;
  71131. this._attachedCamera = camera;
  71132. var scene = this._attachedCamera.getScene();
  71133. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  71134. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71135. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71136. _this._isPointerDown = true;
  71137. return;
  71138. }
  71139. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71140. _this._isPointerDown = false;
  71141. }
  71142. });
  71143. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71144. if (mesh) {
  71145. _this.zoomOnMesh(mesh);
  71146. }
  71147. });
  71148. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71149. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71150. _this._applyUserInteraction();
  71151. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  71152. // back to the default position after a given timeout
  71153. _this._maintainCameraAboveGround();
  71154. });
  71155. };
  71156. FramingBehavior.prototype.detach = function () {
  71157. var scene = this._attachedCamera.getScene();
  71158. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71159. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71160. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71161. this._attachedCamera = null;
  71162. };
  71163. /**
  71164. * Targets the given mesh and updates zoom level accordingly.
  71165. * @param mesh The mesh to target.
  71166. * @param radius Optional. If a cached radius position already exists, overrides default.
  71167. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71168. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71169. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71170. */
  71171. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  71172. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71173. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71174. mesh.computeWorldMatrix(true);
  71175. var boundingBox = mesh.getBoundingInfo().boundingBox;
  71176. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  71177. };
  71178. /**
  71179. * Targets the given mesh and updates zoom level accordingly.
  71180. * @param mesh The mesh to target.
  71181. * @param radius Optional. If a cached radius position already exists, overrides default.
  71182. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71183. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71184. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71185. */
  71186. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  71187. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71188. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71189. var zoomTarget;
  71190. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  71191. var bottom = minimumWorld.y;
  71192. var top = maximumWorld.y;
  71193. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  71194. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  71195. if (focusOnOriginXZ) {
  71196. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  71197. }
  71198. else {
  71199. var centerWorld = minimumWorld.add(radiusWorld);
  71200. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  71201. }
  71202. if (!this._vectorTransition) {
  71203. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  71204. }
  71205. this._betaIsAnimating = true;
  71206. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  71207. // sets the radius and lower radius bounds
  71208. // Small delta ensures camera is not always at lower zoom limit.
  71209. var delta = 0.1;
  71210. var radius = 0;
  71211. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  71212. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71213. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  71214. radius = position;
  71215. }
  71216. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71217. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71218. if (this._attachedCamera.lowerRadiusLimit === null) {
  71219. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  71220. }
  71221. }
  71222. // transition to new radius
  71223. if (!this._radiusTransition) {
  71224. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71225. }
  71226. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, onAnimationEnd));
  71227. };
  71228. /**
  71229. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  71230. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  71231. * frustum width.
  71232. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  71233. * to fully enclose the mesh in the viewing frustum.
  71234. */
  71235. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  71236. var size = maximumWorld.subtract(minimumWorld);
  71237. var boxVectorGlobalDiagonal = size.length();
  71238. var frustumSlope = this._getFrustumSlope();
  71239. // Formula for setting distance
  71240. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  71241. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  71242. // Horizon distance
  71243. var radius = radiusWithoutFraming * this._radiusScale;
  71244. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  71245. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  71246. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  71247. var camera = this._attachedCamera;
  71248. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71249. // Don't exceed the requested limit
  71250. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  71251. }
  71252. // Don't exceed the upper radius limit
  71253. if (camera.upperRadiusLimit) {
  71254. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  71255. }
  71256. return distance;
  71257. };
  71258. /**
  71259. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  71260. * is automatically returned to its default position (expected to be above ground plane).
  71261. */
  71262. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  71263. var _this = this;
  71264. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  71265. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  71266. var limitBeta = Math.PI * 0.5;
  71267. // Bring the camera back up if below the ground plane
  71268. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  71269. this._betaIsAnimating = true;
  71270. //Transition to new position
  71271. this.stopAllAnimations();
  71272. if (!this._betaTransition) {
  71273. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71274. }
  71275. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  71276. _this._clearAnimationLocks();
  71277. _this.stopAllAnimations();
  71278. }));
  71279. }
  71280. };
  71281. /**
  71282. * Returns the frustum slope based on the canvas ratio and camera FOV
  71283. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  71284. */
  71285. FramingBehavior.prototype._getFrustumSlope = function () {
  71286. // Calculate the viewport ratio
  71287. // Aspect Ratio is Height/Width.
  71288. var camera = this._attachedCamera;
  71289. var engine = camera.getScene().getEngine();
  71290. var aspectRatio = engine.getAspectRatio(camera);
  71291. // Camera FOV is the vertical field of view (top-bottom) in radians.
  71292. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  71293. var frustumSlopeY = Math.tan(camera.fov / 2);
  71294. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  71295. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  71296. // along the forward vector.
  71297. var frustumSlopeX = frustumSlopeY * aspectRatio;
  71298. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  71299. };
  71300. /**
  71301. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  71302. */
  71303. FramingBehavior.prototype._clearAnimationLocks = function () {
  71304. this._betaIsAnimating = false;
  71305. };
  71306. /**
  71307. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71308. */
  71309. FramingBehavior.prototype._applyUserInteraction = function () {
  71310. if (this.isUserIsMoving) {
  71311. this._lastInteractionTime = BABYLON.Tools.Now;
  71312. this.stopAllAnimations();
  71313. this._clearAnimationLocks();
  71314. }
  71315. };
  71316. /**
  71317. * Stops and removes all animations that have been applied to the camera
  71318. */
  71319. FramingBehavior.prototype.stopAllAnimations = function () {
  71320. this._attachedCamera.animations = [];
  71321. while (this._animatables.length) {
  71322. if (this._animatables[0]) {
  71323. this._animatables[0].onAnimationEnd = null;
  71324. this._animatables[0].stop();
  71325. }
  71326. this._animatables.shift();
  71327. }
  71328. };
  71329. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  71330. /**
  71331. * Gets a value indicating if the user is moving the camera
  71332. */
  71333. get: function () {
  71334. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71335. this._attachedCamera.inertialBetaOffset !== 0 ||
  71336. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71337. this._attachedCamera.inertialPanningX !== 0 ||
  71338. this._attachedCamera.inertialPanningY !== 0 ||
  71339. this._isPointerDown;
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. /**
  71345. * The easing function used by animations
  71346. */
  71347. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  71348. /**
  71349. * The easing mode used by animations
  71350. */
  71351. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  71352. // Statics
  71353. /**
  71354. * The camera can move all the way towards the mesh.
  71355. */
  71356. FramingBehavior.IgnoreBoundsSizeMode = 0;
  71357. /**
  71358. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  71359. */
  71360. FramingBehavior.FitFrustumSidesMode = 1;
  71361. return FramingBehavior;
  71362. }());
  71363. BABYLON.FramingBehavior = FramingBehavior;
  71364. })(BABYLON || (BABYLON = {}));
  71365. //# sourceMappingURL=babylon.framingBehavior.js.map
  71366. var BABYLON;
  71367. (function (BABYLON) {
  71368. /**
  71369. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  71370. */
  71371. var BouncingBehavior = (function () {
  71372. function BouncingBehavior() {
  71373. /**
  71374. * The duration of the animation, in milliseconds
  71375. */
  71376. this.transitionDuration = 450;
  71377. /**
  71378. * Length of the distance animated by the transition when lower radius is reached
  71379. */
  71380. this.lowerRadiusTransitionRange = 2;
  71381. /**
  71382. * Length of the distance animated by the transition when upper radius is reached
  71383. */
  71384. this.upperRadiusTransitionRange = -2;
  71385. this._autoTransitionRange = false;
  71386. // Animations
  71387. this._radiusIsAnimating = false;
  71388. this._radiusBounceTransition = null;
  71389. this._animatables = new Array();
  71390. }
  71391. Object.defineProperty(BouncingBehavior.prototype, "name", {
  71392. get: function () {
  71393. return "Bouncing";
  71394. },
  71395. enumerable: true,
  71396. configurable: true
  71397. });
  71398. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  71399. /**
  71400. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71401. */
  71402. get: function () {
  71403. return this._autoTransitionRange;
  71404. },
  71405. /**
  71406. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71407. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  71408. */
  71409. set: function (value) {
  71410. var _this = this;
  71411. if (this._autoTransitionRange === value) {
  71412. return;
  71413. }
  71414. this._autoTransitionRange = value;
  71415. var camera = this._attachedCamera;
  71416. if (value) {
  71417. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71418. if (!mesh) {
  71419. return;
  71420. }
  71421. mesh.computeWorldMatrix(true);
  71422. var diagonal = mesh.getBoundingInfo().diagonalLength;
  71423. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  71424. _this.upperRadiusTransitionRange = diagonal * 0.05;
  71425. });
  71426. }
  71427. else if (this._onMeshTargetChangedObserver) {
  71428. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71429. }
  71430. },
  71431. enumerable: true,
  71432. configurable: true
  71433. });
  71434. BouncingBehavior.prototype.attach = function (camera) {
  71435. var _this = this;
  71436. this._attachedCamera = camera;
  71437. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71438. // Add the bounce animation to the lower radius limit
  71439. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  71440. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  71441. }
  71442. // Add the bounce animation to the upper radius limit
  71443. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  71444. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  71445. }
  71446. });
  71447. };
  71448. BouncingBehavior.prototype.detach = function () {
  71449. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71450. if (this._onMeshTargetChangedObserver) {
  71451. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71452. }
  71453. this._attachedCamera = null;
  71454. };
  71455. /**
  71456. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  71457. * @param radiusLimit The limit to check against.
  71458. * @return Bool to indicate if at limit.
  71459. */
  71460. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  71461. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  71462. return true;
  71463. }
  71464. return false;
  71465. };
  71466. /**
  71467. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  71468. * @param radiusDelta The delta by which to animate to. Can be negative.
  71469. */
  71470. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  71471. var _this = this;
  71472. if (!this._radiusBounceTransition) {
  71473. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  71474. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  71475. }
  71476. // Prevent zoom until bounce has completed
  71477. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  71478. this._attachedCamera.wheelPrecision = Infinity;
  71479. this._attachedCamera.inertialRadiusOffset = 0;
  71480. // Animate to the radius limit
  71481. this.stopAllAnimations();
  71482. this._radiusIsAnimating = true;
  71483. 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(); }));
  71484. };
  71485. /**
  71486. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  71487. */
  71488. BouncingBehavior.prototype._clearAnimationLocks = function () {
  71489. this._radiusIsAnimating = false;
  71490. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  71491. };
  71492. /**
  71493. * Stops and removes all animations that have been applied to the camera
  71494. */
  71495. BouncingBehavior.prototype.stopAllAnimations = function () {
  71496. this._attachedCamera.animations = [];
  71497. while (this._animatables.length) {
  71498. this._animatables[0].onAnimationEnd = null;
  71499. this._animatables[0].stop();
  71500. this._animatables.shift();
  71501. }
  71502. };
  71503. /**
  71504. * The easing function used by animations
  71505. */
  71506. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  71507. /**
  71508. * The easing mode used by animations
  71509. */
  71510. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  71511. return BouncingBehavior;
  71512. }());
  71513. BABYLON.BouncingBehavior = BouncingBehavior;
  71514. })(BABYLON || (BABYLON = {}));
  71515. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  71516. var BABYLON;
  71517. (function (BABYLON) {
  71518. var AutoRotationBehavior = (function () {
  71519. function AutoRotationBehavior() {
  71520. this._zoomStopsAnimation = false;
  71521. this._idleRotationSpeed = 0.05;
  71522. this._idleRotationWaitTime = 2000;
  71523. this._idleRotationSpinupTime = 2000;
  71524. this._isPointerDown = false;
  71525. this._lastFrameTime = null;
  71526. this._lastInteractionTime = -Infinity;
  71527. this._cameraRotationSpeed = 0;
  71528. this._lastFrameRadius = 0;
  71529. }
  71530. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  71531. get: function () {
  71532. return "AutoRotation";
  71533. },
  71534. enumerable: true,
  71535. configurable: true
  71536. });
  71537. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  71538. /**
  71539. * Gets the flag that indicates if user zooming should stop animation.
  71540. */
  71541. get: function () {
  71542. return this._zoomStopsAnimation;
  71543. },
  71544. /**
  71545. * Sets the flag that indicates if user zooming should stop animation.
  71546. */
  71547. set: function (flag) {
  71548. this._zoomStopsAnimation = flag;
  71549. },
  71550. enumerable: true,
  71551. configurable: true
  71552. });
  71553. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  71554. /**
  71555. * Gets the default speed at which the camera rotates around the model.
  71556. */
  71557. get: function () {
  71558. return this._idleRotationSpeed;
  71559. },
  71560. /**
  71561. * Sets the default speed at which the camera rotates around the model.
  71562. */
  71563. set: function (speed) {
  71564. this._idleRotationSpeed = speed;
  71565. },
  71566. enumerable: true,
  71567. configurable: true
  71568. });
  71569. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  71570. /**
  71571. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  71572. */
  71573. get: function () {
  71574. return this._idleRotationWaitTime;
  71575. },
  71576. /**
  71577. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  71578. */
  71579. set: function (time) {
  71580. this._idleRotationWaitTime = time;
  71581. },
  71582. enumerable: true,
  71583. configurable: true
  71584. });
  71585. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  71586. /**
  71587. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71588. */
  71589. get: function () {
  71590. return this._idleRotationSpinupTime;
  71591. },
  71592. /**
  71593. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71594. */
  71595. set: function (time) {
  71596. this._idleRotationSpinupTime = time;
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  71602. /**
  71603. * Gets a value indicating if the camera is currently rotating because of this behavior
  71604. */
  71605. get: function () {
  71606. return Math.abs(this._cameraRotationSpeed) > 0;
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. AutoRotationBehavior.prototype.attach = function (camera) {
  71612. var _this = this;
  71613. this._attachedCamera = camera;
  71614. var scene = this._attachedCamera.getScene();
  71615. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71616. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71617. _this._isPointerDown = true;
  71618. return;
  71619. }
  71620. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71621. _this._isPointerDown = false;
  71622. }
  71623. });
  71624. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71625. var now = BABYLON.Tools.Now;
  71626. var dt = 0;
  71627. if (_this._lastFrameTime != null) {
  71628. dt = now - _this._lastFrameTime;
  71629. }
  71630. _this._lastFrameTime = now;
  71631. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71632. _this._applyUserInteraction();
  71633. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  71634. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  71635. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  71636. // Step camera rotation by rotation speed
  71637. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  71638. });
  71639. };
  71640. AutoRotationBehavior.prototype.detach = function () {
  71641. var scene = this._attachedCamera.getScene();
  71642. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71643. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71644. this._attachedCamera = null;
  71645. };
  71646. /**
  71647. * Returns true if user is scrolling.
  71648. * @return true if user is scrolling.
  71649. */
  71650. AutoRotationBehavior.prototype._userIsZooming = function () {
  71651. return this._attachedCamera.inertialRadiusOffset !== 0;
  71652. };
  71653. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  71654. var zoomHasHitLimit = false;
  71655. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  71656. zoomHasHitLimit = true;
  71657. }
  71658. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  71659. this._lastFrameRadius = this._attachedCamera.radius;
  71660. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  71661. };
  71662. /**
  71663. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71664. */
  71665. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  71666. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  71667. this._lastInteractionTime = BABYLON.Tools.Now;
  71668. }
  71669. };
  71670. // Tools
  71671. AutoRotationBehavior.prototype._userIsMoving = function () {
  71672. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71673. this._attachedCamera.inertialBetaOffset !== 0 ||
  71674. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71675. this._attachedCamera.inertialPanningX !== 0 ||
  71676. this._attachedCamera.inertialPanningY !== 0 ||
  71677. this._isPointerDown;
  71678. };
  71679. return AutoRotationBehavior;
  71680. }());
  71681. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  71682. })(BABYLON || (BABYLON = {}));
  71683. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  71684. 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#include<depthPrePass>\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\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\nfloat comp=sign(dot(normalW,faceNormal));\nnormalW*=-comp;\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;\n\nuniform mat4 view;\nuniform mat4 projection;\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;\nvUV=offset;\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}"};
  71685. 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 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\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 vec4 vNormalReoderParams;\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 vNormalReoderParams;\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 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap.x=vNormalReoderParams.x+vNormalReoderParams.y*map.x;\nmap.y=vNormalReoderParams.z+vNormalReoderParams.w*map.y;\nmap=map*255./127.-128./127.;\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 vec4 vNormalReoderParams;\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 vec4 vNormalReoderParams;\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};"};
  71686. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  71687. var BABYLON;
  71688. (function (BABYLON) {
  71689. var GridMaterialDefines = (function (_super) {
  71690. __extends(GridMaterialDefines, _super);
  71691. function GridMaterialDefines() {
  71692. var _this = _super.call(this) || this;
  71693. _this.TRANSPARENT = false;
  71694. _this.FOG = false;
  71695. _this.PREMULTIPLYALPHA = false;
  71696. _this.rebuild();
  71697. return _this;
  71698. }
  71699. return GridMaterialDefines;
  71700. }(BABYLON.MaterialDefines));
  71701. /**
  71702. * The grid materials allows you to wrap any shape with a grid.
  71703. * Colors are customizable.
  71704. */
  71705. var GridMaterial = (function (_super) {
  71706. __extends(GridMaterial, _super);
  71707. /**
  71708. * constructor
  71709. * @param name The name given to the material in order to identify it afterwards.
  71710. * @param scene The scene the material is used in.
  71711. */
  71712. function GridMaterial(name, scene) {
  71713. var _this = _super.call(this, name, scene) || this;
  71714. /**
  71715. * Main color of the grid (e.g. between lines)
  71716. */
  71717. _this.mainColor = BABYLON.Color3.Black();
  71718. /**
  71719. * Color of the grid lines.
  71720. */
  71721. _this.lineColor = BABYLON.Color3.Teal();
  71722. /**
  71723. * The scale of the grid compared to unit.
  71724. */
  71725. _this.gridRatio = 1.0;
  71726. /**
  71727. * The frequency of thicker lines.
  71728. */
  71729. _this.majorUnitFrequency = 10;
  71730. /**
  71731. * The visibility of minor units in the grid.
  71732. */
  71733. _this.minorUnitVisibility = 0.33;
  71734. /**
  71735. * The grid opacity outside of the lines.
  71736. */
  71737. _this.opacity = 1.0;
  71738. /**
  71739. * Determine RBG output is premultiplied by alpha value.
  71740. */
  71741. _this.preMultiplyAlpha = false;
  71742. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  71743. return _this;
  71744. }
  71745. /**
  71746. * Returns wehter or not the grid requires alpha blending.
  71747. */
  71748. GridMaterial.prototype.needAlphaBlending = function () {
  71749. return this.opacity < 1.0;
  71750. };
  71751. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71752. if (this.isFrozen) {
  71753. if (this._wasPreviouslyReady && subMesh.effect) {
  71754. return true;
  71755. }
  71756. }
  71757. if (!subMesh._materialDefines) {
  71758. subMesh._materialDefines = new GridMaterialDefines();
  71759. }
  71760. var defines = subMesh._materialDefines;
  71761. var scene = this.getScene();
  71762. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  71763. if (this._renderId === scene.getRenderId()) {
  71764. return true;
  71765. }
  71766. }
  71767. var engine = scene.getEngine();
  71768. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  71769. defines.TRANSPARENT = !defines.TRANSPARENT;
  71770. defines.markAsUnprocessed();
  71771. }
  71772. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  71773. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  71774. defines.markAsUnprocessed();
  71775. }
  71776. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  71777. // Get correct effect
  71778. if (defines.isDirty) {
  71779. defines.markAsProcessed();
  71780. scene.resetCachedMaterial();
  71781. // Attributes
  71782. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71783. // Defines
  71784. var join = defines.toString();
  71785. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  71786. }
  71787. if (!subMesh.effect.isReady()) {
  71788. return false;
  71789. }
  71790. this._renderId = scene.getRenderId();
  71791. this._wasPreviouslyReady = true;
  71792. return true;
  71793. };
  71794. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  71795. var scene = this.getScene();
  71796. var defines = subMesh._materialDefines;
  71797. if (!defines) {
  71798. return;
  71799. }
  71800. var effect = subMesh.effect;
  71801. this._activeEffect = effect;
  71802. // Matrices
  71803. this.bindOnlyWorldMatrix(world);
  71804. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  71805. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  71806. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  71807. // Uniforms
  71808. if (this._mustRebind(scene, effect)) {
  71809. this._activeEffect.setColor3("mainColor", this.mainColor);
  71810. this._activeEffect.setColor3("lineColor", this.lineColor);
  71811. this._gridControl.x = this.gridRatio;
  71812. this._gridControl.y = Math.round(this.majorUnitFrequency);
  71813. this._gridControl.z = this.minorUnitVisibility;
  71814. this._gridControl.w = this.opacity;
  71815. this._activeEffect.setVector4("gridControl", this._gridControl);
  71816. }
  71817. // Fog
  71818. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  71819. this._afterBind(mesh, this._activeEffect);
  71820. };
  71821. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  71822. _super.prototype.dispose.call(this, forceDisposeEffect);
  71823. };
  71824. GridMaterial.prototype.clone = function (name) {
  71825. var _this = this;
  71826. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  71827. };
  71828. GridMaterial.prototype.serialize = function () {
  71829. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71830. serializationObject.customType = "BABYLON.GridMaterial";
  71831. return serializationObject;
  71832. };
  71833. GridMaterial.prototype.getClassName = function () {
  71834. return "GridMaterial";
  71835. };
  71836. GridMaterial.Parse = function (source, scene, rootUrl) {
  71837. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  71838. };
  71839. __decorate([
  71840. BABYLON.serializeAsColor3()
  71841. ], GridMaterial.prototype, "mainColor", void 0);
  71842. __decorate([
  71843. BABYLON.serializeAsColor3()
  71844. ], GridMaterial.prototype, "lineColor", void 0);
  71845. __decorate([
  71846. BABYLON.serialize()
  71847. ], GridMaterial.prototype, "gridRatio", void 0);
  71848. __decorate([
  71849. BABYLON.serialize()
  71850. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  71851. __decorate([
  71852. BABYLON.serialize()
  71853. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  71854. __decorate([
  71855. BABYLON.serialize()
  71856. ], GridMaterial.prototype, "opacity", void 0);
  71857. __decorate([
  71858. BABYLON.serialize()
  71859. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  71860. return GridMaterial;
  71861. }(BABYLON.PushMaterial));
  71862. BABYLON.GridMaterial = GridMaterial;
  71863. })(BABYLON || (BABYLON = {}));
  71864. //# sourceMappingURL=babylon.gridmaterial.js.map
  71865. 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}";
  71866. 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;\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/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}";
  71867. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  71868. var BABYLON;
  71869. (function (BABYLON) {
  71870. var GLTFLoaderCoordinateSystemMode;
  71871. (function (GLTFLoaderCoordinateSystemMode) {
  71872. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  71873. // 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.
  71874. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  71875. // The glTF right-handed data is not transformed in any form and is loaded directly.
  71876. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  71877. // Sets the useRightHandedSystem flag on the scene.
  71878. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  71879. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  71880. var GLTFFileLoader = (function () {
  71881. function GLTFFileLoader() {
  71882. // V2 options
  71883. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  71884. this.name = "gltf";
  71885. this.extensions = {
  71886. ".gltf": { isBinary: false },
  71887. ".glb": { isBinary: true }
  71888. };
  71889. }
  71890. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  71891. var loaderData = GLTFFileLoader._parse(data, onError);
  71892. if (!loaderData) {
  71893. return;
  71894. }
  71895. var loader = this._getLoader(loaderData, onError);
  71896. if (!loader) {
  71897. return;
  71898. }
  71899. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  71900. };
  71901. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  71902. var loaderData = GLTFFileLoader._parse(data, onError);
  71903. if (!loaderData) {
  71904. return;
  71905. }
  71906. var loader = this._getLoader(loaderData, onError);
  71907. if (!loader) {
  71908. return;
  71909. }
  71910. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  71911. };
  71912. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  71913. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  71914. };
  71915. GLTFFileLoader._parse = function (data, onError) {
  71916. if (data instanceof ArrayBuffer) {
  71917. return GLTFFileLoader._parseBinary(data, onError);
  71918. }
  71919. try {
  71920. return {
  71921. json: JSON.parse(data),
  71922. bin: null
  71923. };
  71924. }
  71925. catch (e) {
  71926. onError(e.message);
  71927. return null;
  71928. }
  71929. };
  71930. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  71931. var loaderVersion = { major: 2, minor: 0 };
  71932. var asset = loaderData.json.asset || {};
  71933. var version = GLTFFileLoader._parseVersion(asset.version);
  71934. if (!version) {
  71935. onError("Invalid version: " + asset.version);
  71936. return null;
  71937. }
  71938. if (asset.minVersion !== undefined) {
  71939. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  71940. if (!minVersion) {
  71941. onError("Invalid minimum version: " + asset.minVersion);
  71942. return null;
  71943. }
  71944. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  71945. onError("Incompatible minimum version: " + asset.minVersion);
  71946. return null;
  71947. }
  71948. }
  71949. var createLoaders = {
  71950. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  71951. 2: GLTFFileLoader.CreateGLTFLoaderV2
  71952. };
  71953. var createLoader = createLoaders[version.major];
  71954. if (!createLoader) {
  71955. onError("Unsupported version: " + asset.version);
  71956. return null;
  71957. }
  71958. return createLoader(this);
  71959. };
  71960. GLTFFileLoader._parseBinary = function (data, onError) {
  71961. var Binary = {
  71962. Magic: 0x46546C67
  71963. };
  71964. var binaryReader = new BinaryReader(data);
  71965. var magic = binaryReader.readUint32();
  71966. if (magic !== Binary.Magic) {
  71967. onError("Unexpected magic: " + magic);
  71968. return null;
  71969. }
  71970. var version = binaryReader.readUint32();
  71971. switch (version) {
  71972. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  71973. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  71974. }
  71975. onError("Unsupported version: " + version);
  71976. return null;
  71977. };
  71978. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  71979. var ContentFormat = {
  71980. JSON: 0
  71981. };
  71982. var length = binaryReader.readUint32();
  71983. if (length != binaryReader.getLength()) {
  71984. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  71985. return null;
  71986. }
  71987. var contentLength = binaryReader.readUint32();
  71988. var contentFormat = binaryReader.readUint32();
  71989. var content;
  71990. switch (contentFormat) {
  71991. case ContentFormat.JSON:
  71992. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  71993. break;
  71994. default:
  71995. onError("Unexpected content format: " + contentFormat);
  71996. return null;
  71997. }
  71998. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  71999. var body = binaryReader.readUint8Array(bytesRemaining);
  72000. return {
  72001. json: content,
  72002. bin: body
  72003. };
  72004. };
  72005. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  72006. var ChunkFormat = {
  72007. JSON: 0x4E4F534A,
  72008. BIN: 0x004E4942
  72009. };
  72010. var length = binaryReader.readUint32();
  72011. if (length !== binaryReader.getLength()) {
  72012. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72013. return null;
  72014. }
  72015. // JSON chunk
  72016. var chunkLength = binaryReader.readUint32();
  72017. var chunkFormat = binaryReader.readUint32();
  72018. if (chunkFormat !== ChunkFormat.JSON) {
  72019. onError("First chunk format is not JSON");
  72020. return null;
  72021. }
  72022. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  72023. // Look for BIN chunk
  72024. var bin = null;
  72025. while (binaryReader.getPosition() < binaryReader.getLength()) {
  72026. chunkLength = binaryReader.readUint32();
  72027. chunkFormat = binaryReader.readUint32();
  72028. switch (chunkFormat) {
  72029. case ChunkFormat.JSON:
  72030. onError("Unexpected JSON chunk");
  72031. return null;
  72032. case ChunkFormat.BIN:
  72033. bin = binaryReader.readUint8Array(chunkLength);
  72034. break;
  72035. default:
  72036. // ignore unrecognized chunkFormat
  72037. binaryReader.skipBytes(chunkLength);
  72038. break;
  72039. }
  72040. }
  72041. return {
  72042. json: json,
  72043. bin: bin
  72044. };
  72045. };
  72046. GLTFFileLoader._parseVersion = function (version) {
  72047. if (!version) {
  72048. return null;
  72049. }
  72050. var parts = version.split(".");
  72051. if (parts.length != 2) {
  72052. return null;
  72053. }
  72054. var major = +parts[0];
  72055. if (isNaN(major)) {
  72056. return null;
  72057. }
  72058. var minor = +parts[1];
  72059. if (isNaN(minor)) {
  72060. return null;
  72061. }
  72062. return {
  72063. major: major,
  72064. minor: minor
  72065. };
  72066. };
  72067. GLTFFileLoader._compareVersion = function (a, b) {
  72068. if (a.major > b.major)
  72069. return 1;
  72070. if (a.major < b.major)
  72071. return -1;
  72072. if (a.minor > b.minor)
  72073. return 1;
  72074. if (a.minor < b.minor)
  72075. return -1;
  72076. return 0;
  72077. };
  72078. GLTFFileLoader._decodeBufferToText = function (view) {
  72079. var result = "";
  72080. var length = view.byteLength;
  72081. for (var i = 0; i < length; ++i) {
  72082. result += String.fromCharCode(view[i]);
  72083. }
  72084. return result;
  72085. };
  72086. // V1 options
  72087. GLTFFileLoader.HomogeneousCoordinates = false;
  72088. GLTFFileLoader.IncrementalLoading = true;
  72089. return GLTFFileLoader;
  72090. }());
  72091. BABYLON.GLTFFileLoader = GLTFFileLoader;
  72092. var BinaryReader = (function () {
  72093. function BinaryReader(arrayBuffer) {
  72094. this._arrayBuffer = arrayBuffer;
  72095. this._dataView = new DataView(arrayBuffer);
  72096. this._byteOffset = 0;
  72097. }
  72098. BinaryReader.prototype.getPosition = function () {
  72099. return this._byteOffset;
  72100. };
  72101. BinaryReader.prototype.getLength = function () {
  72102. return this._arrayBuffer.byteLength;
  72103. };
  72104. BinaryReader.prototype.readUint32 = function () {
  72105. var value = this._dataView.getUint32(this._byteOffset, true);
  72106. this._byteOffset += 4;
  72107. return value;
  72108. };
  72109. BinaryReader.prototype.readUint8Array = function (length) {
  72110. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  72111. this._byteOffset += length;
  72112. return value;
  72113. };
  72114. BinaryReader.prototype.skipBytes = function (length) {
  72115. this._byteOffset += length;
  72116. };
  72117. return BinaryReader;
  72118. }());
  72119. if (BABYLON.SceneLoader) {
  72120. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  72121. }
  72122. })(BABYLON || (BABYLON = {}));
  72123. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  72124. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72125. var BABYLON;
  72126. (function (BABYLON) {
  72127. var GLTF1;
  72128. (function (GLTF1) {
  72129. /**
  72130. * Enums
  72131. */
  72132. var EComponentType;
  72133. (function (EComponentType) {
  72134. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  72135. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72136. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  72137. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72138. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  72139. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  72140. var EShaderType;
  72141. (function (EShaderType) {
  72142. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  72143. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  72144. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  72145. var EParameterType;
  72146. (function (EParameterType) {
  72147. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  72148. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72149. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  72150. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72151. EParameterType[EParameterType["INT"] = 5124] = "INT";
  72152. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  72153. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  72154. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  72155. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  72156. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  72157. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  72158. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  72159. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  72160. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  72161. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  72162. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  72163. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  72164. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  72165. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  72166. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  72167. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  72168. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  72169. var ETextureWrapMode;
  72170. (function (ETextureWrapMode) {
  72171. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  72172. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  72173. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  72174. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  72175. var ETextureFilterType;
  72176. (function (ETextureFilterType) {
  72177. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  72178. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  72179. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  72180. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  72181. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  72182. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  72183. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  72184. var ETextureFormat;
  72185. (function (ETextureFormat) {
  72186. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  72187. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  72188. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  72189. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  72190. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  72191. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  72192. var ECullingType;
  72193. (function (ECullingType) {
  72194. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  72195. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  72196. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72197. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  72198. var EBlendingFunction;
  72199. (function (EBlendingFunction) {
  72200. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  72201. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  72202. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  72203. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  72204. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  72205. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  72206. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  72207. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  72208. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  72209. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  72210. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  72211. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  72212. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  72213. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  72214. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  72215. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  72216. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  72217. })(BABYLON || (BABYLON = {}));
  72218. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  72219. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72220. var BABYLON;
  72221. (function (BABYLON) {
  72222. var GLTF1;
  72223. (function (GLTF1) {
  72224. /**
  72225. * Tokenizer. Used for shaders compatibility
  72226. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  72227. */
  72228. var ETokenType;
  72229. (function (ETokenType) {
  72230. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  72231. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  72232. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  72233. })(ETokenType || (ETokenType = {}));
  72234. var Tokenizer = (function () {
  72235. function Tokenizer(toParse) {
  72236. this._pos = 0;
  72237. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  72238. this._toParse = toParse;
  72239. this._maxPos = toParse.length;
  72240. }
  72241. Tokenizer.prototype.getNextToken = function () {
  72242. if (this.isEnd())
  72243. return ETokenType.END_OF_INPUT;
  72244. this.currentString = this.read();
  72245. this.currentToken = ETokenType.UNKNOWN;
  72246. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  72247. this.currentToken = ETokenType.IDENTIFIER;
  72248. this.currentIdentifier = this.currentString;
  72249. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  72250. this.currentIdentifier += this.currentString;
  72251. this.forward();
  72252. }
  72253. }
  72254. return this.currentToken;
  72255. };
  72256. Tokenizer.prototype.peek = function () {
  72257. return this._toParse[this._pos];
  72258. };
  72259. Tokenizer.prototype.read = function () {
  72260. return this._toParse[this._pos++];
  72261. };
  72262. Tokenizer.prototype.forward = function () {
  72263. this._pos++;
  72264. };
  72265. Tokenizer.prototype.isEnd = function () {
  72266. return this._pos >= this._maxPos;
  72267. };
  72268. return Tokenizer;
  72269. }());
  72270. /**
  72271. * Values
  72272. */
  72273. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  72274. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  72275. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  72276. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  72277. /**
  72278. * Parse
  72279. */
  72280. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  72281. for (var buf in parsedBuffers) {
  72282. var parsedBuffer = parsedBuffers[buf];
  72283. gltfRuntime.buffers[buf] = parsedBuffer;
  72284. gltfRuntime.buffersCount++;
  72285. }
  72286. };
  72287. var parseShaders = function (parsedShaders, gltfRuntime) {
  72288. for (var sha in parsedShaders) {
  72289. var parsedShader = parsedShaders[sha];
  72290. gltfRuntime.shaders[sha] = parsedShader;
  72291. gltfRuntime.shaderscount++;
  72292. }
  72293. };
  72294. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  72295. for (var object in parsedObjects) {
  72296. var parsedObject = parsedObjects[object];
  72297. gltfRuntime[runtimeProperty][object] = parsedObject;
  72298. }
  72299. };
  72300. /**
  72301. * Utils
  72302. */
  72303. var normalizeUVs = function (buffer) {
  72304. if (!buffer) {
  72305. return;
  72306. }
  72307. for (var i = 0; i < buffer.length / 2; i++) {
  72308. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  72309. }
  72310. };
  72311. var replaceInString = function (str, searchValue, replaceValue) {
  72312. while (str.indexOf(searchValue) !== -1) {
  72313. str = str.replace(searchValue, replaceValue);
  72314. }
  72315. return str;
  72316. };
  72317. var getAttribute = function (attributeParameter) {
  72318. if (attributeParameter.semantic === "NORMAL") {
  72319. return "normal";
  72320. }
  72321. else if (attributeParameter.semantic === "POSITION") {
  72322. return "position";
  72323. }
  72324. else if (attributeParameter.semantic === "JOINT") {
  72325. return "matricesIndices";
  72326. }
  72327. else if (attributeParameter.semantic === "WEIGHT") {
  72328. return "matricesWeights";
  72329. }
  72330. else if (attributeParameter.semantic === "COLOR") {
  72331. return "color";
  72332. }
  72333. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  72334. var channel = Number(attributeParameter.semantic.split("_")[1]);
  72335. return "uv" + (channel === 0 ? "" : channel + 1);
  72336. }
  72337. };
  72338. /**
  72339. * Returns the animation path (glTF -> Babylon)
  72340. */
  72341. var getAnimationPath = function (path) {
  72342. var index = glTFAnimationPaths.indexOf(path);
  72343. if (index !== -1) {
  72344. return babylonAnimationPaths[index];
  72345. }
  72346. return path;
  72347. };
  72348. /**
  72349. * Loads and creates animations
  72350. */
  72351. var loadAnimations = function (gltfRuntime) {
  72352. for (var anim in gltfRuntime.animations) {
  72353. var animation = gltfRuntime.animations[anim];
  72354. var lastAnimation = null;
  72355. for (var i = 0; i < animation.channels.length; i++) {
  72356. // Get parameters and load buffers
  72357. var channel = animation.channels[i];
  72358. var sampler = animation.samplers[channel.sampler];
  72359. if (!sampler) {
  72360. continue;
  72361. }
  72362. var inputData = null;
  72363. var outputData = null;
  72364. if (animation.parameters) {
  72365. inputData = animation.parameters[sampler.input];
  72366. outputData = animation.parameters[sampler.output];
  72367. }
  72368. else {
  72369. inputData = sampler.input;
  72370. outputData = sampler.output;
  72371. }
  72372. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  72373. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  72374. var targetID = channel.target.id;
  72375. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  72376. if (targetNode === null) {
  72377. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  72378. }
  72379. if (targetNode === null) {
  72380. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  72381. continue;
  72382. }
  72383. var isBone = targetNode instanceof BABYLON.Bone;
  72384. // Get target path (position, rotation or scaling)
  72385. var targetPath = channel.target.path;
  72386. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  72387. if (targetPathIndex !== -1) {
  72388. targetPath = babylonAnimationPaths[targetPathIndex];
  72389. }
  72390. // Determine animation type
  72391. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  72392. if (!isBone) {
  72393. if (targetPath === "rotationQuaternion") {
  72394. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  72395. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  72396. }
  72397. else {
  72398. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  72399. }
  72400. }
  72401. // Create animation and key frames
  72402. var babylonAnimation = null;
  72403. var keys = [];
  72404. var arrayOffset = 0;
  72405. var modifyKey = false;
  72406. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  72407. babylonAnimation = lastAnimation;
  72408. modifyKey = true;
  72409. }
  72410. if (!modifyKey) {
  72411. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  72412. }
  72413. // For each frame
  72414. for (var j = 0; j < bufferInput.length; j++) {
  72415. var value = null;
  72416. if (targetPath === "rotationQuaternion") {
  72417. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  72418. arrayOffset += 4;
  72419. }
  72420. else {
  72421. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  72422. arrayOffset += 3;
  72423. }
  72424. if (isBone) {
  72425. var bone = targetNode;
  72426. var translation = BABYLON.Vector3.Zero();
  72427. var rotationQuaternion = new BABYLON.Quaternion();
  72428. var scaling = BABYLON.Vector3.Zero();
  72429. // Warning on decompose
  72430. var mat = bone.getBaseMatrix();
  72431. if (modifyKey) {
  72432. mat = lastAnimation.getKeys()[j].value;
  72433. }
  72434. mat.decompose(scaling, rotationQuaternion, translation);
  72435. if (targetPath === "position") {
  72436. translation = value;
  72437. }
  72438. else if (targetPath === "rotationQuaternion") {
  72439. rotationQuaternion = value;
  72440. }
  72441. else {
  72442. scaling = value;
  72443. }
  72444. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  72445. }
  72446. if (!modifyKey) {
  72447. keys.push({
  72448. frame: bufferInput[j],
  72449. value: value
  72450. });
  72451. }
  72452. else {
  72453. lastAnimation.getKeys()[j].value = value;
  72454. }
  72455. }
  72456. // Finish
  72457. if (!modifyKey) {
  72458. babylonAnimation.setKeys(keys);
  72459. targetNode.animations.push(babylonAnimation);
  72460. }
  72461. lastAnimation = babylonAnimation;
  72462. gltfRuntime.scene.stopAnimation(targetNode);
  72463. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  72464. }
  72465. }
  72466. };
  72467. /**
  72468. * Returns the bones transformation matrix
  72469. */
  72470. var configureBoneTransformation = function (node) {
  72471. var mat = null;
  72472. if (node.translation || node.rotation || node.scale) {
  72473. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  72474. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  72475. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  72476. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  72477. }
  72478. else {
  72479. mat = BABYLON.Matrix.FromArray(node.matrix);
  72480. }
  72481. return mat;
  72482. };
  72483. /**
  72484. * Returns the parent bone
  72485. */
  72486. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  72487. // Try to find
  72488. for (var i = 0; i < newSkeleton.bones.length; i++) {
  72489. if (newSkeleton.bones[i].name === jointName) {
  72490. return newSkeleton.bones[i];
  72491. }
  72492. }
  72493. // Not found, search in gltf nodes
  72494. var nodes = gltfRuntime.nodes;
  72495. for (var nde in nodes) {
  72496. var node = nodes[nde];
  72497. if (!node.jointName) {
  72498. continue;
  72499. }
  72500. var children = node.children;
  72501. for (var i = 0; i < children.length; i++) {
  72502. var child = gltfRuntime.nodes[children[i]];
  72503. if (!child.jointName) {
  72504. continue;
  72505. }
  72506. if (child.jointName === jointName) {
  72507. var mat = configureBoneTransformation(node);
  72508. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  72509. bone.id = nde;
  72510. return bone;
  72511. }
  72512. }
  72513. }
  72514. return null;
  72515. };
  72516. /**
  72517. * Returns the appropriate root node
  72518. */
  72519. var getNodeToRoot = function (nodesToRoot, id) {
  72520. for (var i = 0; i < nodesToRoot.length; i++) {
  72521. var nodeToRoot = nodesToRoot[i];
  72522. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  72523. var child = nodeToRoot.node.children[j];
  72524. if (child === id) {
  72525. return nodeToRoot.bone;
  72526. }
  72527. }
  72528. }
  72529. return null;
  72530. };
  72531. /**
  72532. * Returns the node with the joint name
  72533. */
  72534. var getJointNode = function (gltfRuntime, jointName) {
  72535. var nodes = gltfRuntime.nodes;
  72536. var node = nodes[jointName];
  72537. if (node) {
  72538. return {
  72539. node: node,
  72540. id: jointName
  72541. };
  72542. }
  72543. for (var nde in nodes) {
  72544. node = nodes[nde];
  72545. if (node.jointName === jointName) {
  72546. return {
  72547. node: node,
  72548. id: nde
  72549. };
  72550. }
  72551. }
  72552. return null;
  72553. };
  72554. /**
  72555. * Checks if a nodes is in joints
  72556. */
  72557. var nodeIsInJoints = function (skins, id) {
  72558. for (var i = 0; i < skins.jointNames.length; i++) {
  72559. if (skins.jointNames[i] === id) {
  72560. return true;
  72561. }
  72562. }
  72563. return false;
  72564. };
  72565. /**
  72566. * Fills the nodes to root for bones and builds hierarchy
  72567. */
  72568. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  72569. // Creates nodes for root
  72570. for (var nde in gltfRuntime.nodes) {
  72571. var node = gltfRuntime.nodes[nde];
  72572. var id = nde;
  72573. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  72574. continue;
  72575. }
  72576. // Create node to root bone
  72577. var mat = configureBoneTransformation(node);
  72578. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  72579. bone.id = id;
  72580. nodesToRoot.push({ bone: bone, node: node, id: id });
  72581. }
  72582. // Parenting
  72583. for (var i = 0; i < nodesToRoot.length; i++) {
  72584. var nodeToRoot = nodesToRoot[i];
  72585. var children = nodeToRoot.node.children;
  72586. for (var j = 0; j < children.length; j++) {
  72587. var child = null;
  72588. for (var k = 0; k < nodesToRoot.length; k++) {
  72589. if (nodesToRoot[k].id === children[j]) {
  72590. child = nodesToRoot[k];
  72591. break;
  72592. }
  72593. }
  72594. if (child) {
  72595. child.bone._parent = nodeToRoot.bone;
  72596. nodeToRoot.bone.children.push(child.bone);
  72597. }
  72598. }
  72599. }
  72600. };
  72601. var printMat = function (m) {
  72602. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  72603. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  72604. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  72605. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  72606. };
  72607. /**
  72608. * Imports a skeleton
  72609. */
  72610. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  72611. if (!newSkeleton) {
  72612. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  72613. }
  72614. if (!skins.babylonSkeleton) {
  72615. return newSkeleton;
  72616. }
  72617. // Matrices
  72618. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  72619. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72620. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  72621. // Find the root bones
  72622. var nodesToRoot = [];
  72623. var nodesToRootToAdd = [];
  72624. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  72625. newSkeleton.bones = [];
  72626. // Joints
  72627. for (var i = 0; i < skins.jointNames.length; i++) {
  72628. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72629. var node = jointNode.node;
  72630. if (!node) {
  72631. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  72632. continue;
  72633. }
  72634. var id = jointNode.id;
  72635. // Optimize, if the bone already exists...
  72636. var existingBone = gltfRuntime.scene.getBoneByID(id);
  72637. if (existingBone) {
  72638. newSkeleton.bones.push(existingBone);
  72639. continue;
  72640. }
  72641. // Search for parent bone
  72642. var foundBone = false;
  72643. var parentBone = null;
  72644. for (var j = 0; j < i; j++) {
  72645. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  72646. if (!joint) {
  72647. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  72648. continue;
  72649. }
  72650. var children = joint.children;
  72651. if (!children) {
  72652. continue;
  72653. }
  72654. foundBone = false;
  72655. for (var k = 0; k < children.length; k++) {
  72656. if (children[k] === id) {
  72657. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  72658. foundBone = true;
  72659. break;
  72660. }
  72661. }
  72662. if (foundBone) {
  72663. break;
  72664. }
  72665. }
  72666. // Create bone
  72667. var mat = configureBoneTransformation(node);
  72668. if (!parentBone && nodesToRoot.length > 0) {
  72669. parentBone = getNodeToRoot(nodesToRoot, id);
  72670. if (parentBone) {
  72671. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  72672. nodesToRootToAdd.push(parentBone);
  72673. }
  72674. }
  72675. }
  72676. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  72677. bone.id = id;
  72678. }
  72679. // Polish
  72680. var bones = newSkeleton.bones;
  72681. newSkeleton.bones = [];
  72682. for (var i = 0; i < skins.jointNames.length; i++) {
  72683. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72684. if (!jointNode) {
  72685. continue;
  72686. }
  72687. for (var j = 0; j < bones.length; j++) {
  72688. if (bones[j].id === jointNode.id) {
  72689. newSkeleton.bones.push(bones[j]);
  72690. break;
  72691. }
  72692. }
  72693. }
  72694. newSkeleton.prepare();
  72695. // Finish
  72696. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  72697. newSkeleton.bones.push(nodesToRootToAdd[i]);
  72698. }
  72699. return newSkeleton;
  72700. };
  72701. /**
  72702. * Imports a mesh and its geometries
  72703. */
  72704. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  72705. if (!newMesh) {
  72706. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  72707. newMesh.id = id;
  72708. }
  72709. if (!node.babylonNode) {
  72710. return newMesh;
  72711. }
  72712. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  72713. if (!newMesh.material) {
  72714. newMesh.material = multiMat;
  72715. }
  72716. var vertexData = new BABYLON.VertexData();
  72717. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  72718. var verticesStarts = [];
  72719. var verticesCounts = [];
  72720. var indexStarts = [];
  72721. var indexCounts = [];
  72722. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  72723. var meshID = meshes[meshIndex];
  72724. var mesh = gltfRuntime.meshes[meshID];
  72725. if (!mesh) {
  72726. continue;
  72727. }
  72728. // Positions, normals and UVs
  72729. for (var i = 0; i < mesh.primitives.length; i++) {
  72730. // Temporary vertex data
  72731. var tempVertexData = new BABYLON.VertexData();
  72732. var primitive = mesh.primitives[i];
  72733. if (primitive.mode !== 4) {
  72734. // continue;
  72735. }
  72736. var attributes = primitive.attributes;
  72737. var accessor = null;
  72738. var buffer = null;
  72739. // Set positions, normal and uvs
  72740. for (var semantic in attributes) {
  72741. // Link accessor and buffer view
  72742. accessor = gltfRuntime.accessors[attributes[semantic]];
  72743. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72744. if (semantic === "NORMAL") {
  72745. tempVertexData.normals = new Float32Array(buffer.length);
  72746. tempVertexData.normals.set(buffer);
  72747. }
  72748. else if (semantic === "POSITION") {
  72749. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  72750. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  72751. for (var j = 0; j < buffer.length; j += 4) {
  72752. tempVertexData.positions[j] = buffer[j];
  72753. tempVertexData.positions[j + 1] = buffer[j + 1];
  72754. tempVertexData.positions[j + 2] = buffer[j + 2];
  72755. }
  72756. }
  72757. else {
  72758. tempVertexData.positions = new Float32Array(buffer.length);
  72759. tempVertexData.positions.set(buffer);
  72760. }
  72761. verticesCounts.push(tempVertexData.positions.length);
  72762. }
  72763. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  72764. var channel = Number(semantic.split("_")[1]);
  72765. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  72766. var uvs = new Float32Array(buffer.length);
  72767. uvs.set(buffer);
  72768. normalizeUVs(uvs);
  72769. tempVertexData.set(uvs, uvKind);
  72770. }
  72771. else if (semantic === "JOINT") {
  72772. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  72773. tempVertexData.matricesIndices.set(buffer);
  72774. }
  72775. else if (semantic === "WEIGHT") {
  72776. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  72777. tempVertexData.matricesWeights.set(buffer);
  72778. }
  72779. else if (semantic === "COLOR") {
  72780. tempVertexData.colors = new Float32Array(buffer.length);
  72781. tempVertexData.colors.set(buffer);
  72782. }
  72783. }
  72784. // Indices
  72785. accessor = gltfRuntime.accessors[primitive.indices];
  72786. if (accessor) {
  72787. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72788. tempVertexData.indices = new Int32Array(buffer.length);
  72789. tempVertexData.indices.set(buffer);
  72790. indexCounts.push(tempVertexData.indices.length);
  72791. }
  72792. else {
  72793. // Set indices on the fly
  72794. var indices = [];
  72795. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  72796. indices.push(j);
  72797. }
  72798. tempVertexData.indices = new Int32Array(indices);
  72799. indexCounts.push(tempVertexData.indices.length);
  72800. }
  72801. vertexData.merge(tempVertexData);
  72802. tempVertexData = undefined;
  72803. // Sub material
  72804. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  72805. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  72806. // Update vertices start and index start
  72807. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  72808. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  72809. }
  72810. }
  72811. // Apply geometry
  72812. geometry.setAllVerticesData(vertexData, false);
  72813. newMesh.computeWorldMatrix(true);
  72814. // Apply submeshes
  72815. newMesh.subMeshes = [];
  72816. var index = 0;
  72817. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  72818. var meshID = meshes[meshIndex];
  72819. var mesh = gltfRuntime.meshes[meshID];
  72820. if (!mesh) {
  72821. continue;
  72822. }
  72823. for (var i = 0; i < mesh.primitives.length; i++) {
  72824. if (mesh.primitives[i].mode !== 4) {
  72825. //continue;
  72826. }
  72827. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  72828. index++;
  72829. }
  72830. }
  72831. // Finish
  72832. return newMesh;
  72833. };
  72834. /**
  72835. * Configure node transformation from position, rotation and scaling
  72836. */
  72837. var configureNode = function (newNode, position, rotation, scaling) {
  72838. if (newNode.position) {
  72839. newNode.position = position;
  72840. }
  72841. if (newNode.rotationQuaternion || newNode.rotation) {
  72842. newNode.rotationQuaternion = rotation;
  72843. }
  72844. if (newNode.scaling) {
  72845. newNode.scaling = scaling;
  72846. }
  72847. };
  72848. /**
  72849. * Configures node from transformation matrix
  72850. */
  72851. var configureNodeFromMatrix = function (newNode, node, parent) {
  72852. if (node.matrix) {
  72853. var position = new BABYLON.Vector3(0, 0, 0);
  72854. var rotation = new BABYLON.Quaternion();
  72855. var scaling = new BABYLON.Vector3(0, 0, 0);
  72856. var mat = BABYLON.Matrix.FromArray(node.matrix);
  72857. mat.decompose(scaling, rotation, position);
  72858. configureNode(newNode, position, rotation, scaling);
  72859. }
  72860. else {
  72861. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  72862. }
  72863. newNode.computeWorldMatrix(true);
  72864. };
  72865. /**
  72866. * Imports a node
  72867. */
  72868. var importNode = function (gltfRuntime, node, id, parent) {
  72869. var lastNode = null;
  72870. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  72871. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  72872. return null;
  72873. }
  72874. }
  72875. // Meshes
  72876. if (node.skin) {
  72877. if (node.meshes) {
  72878. var skin = gltfRuntime.skins[node.skin];
  72879. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  72880. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  72881. if (newMesh.skeleton === null) {
  72882. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  72883. if (!skin.babylonSkeleton) {
  72884. skin.babylonSkeleton = newMesh.skeleton;
  72885. }
  72886. }
  72887. lastNode = newMesh;
  72888. }
  72889. }
  72890. else if (node.meshes) {
  72891. /**
  72892. * Improve meshes property
  72893. */
  72894. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  72895. lastNode = newMesh;
  72896. }
  72897. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  72898. var light = gltfRuntime.lights[node.light];
  72899. if (light) {
  72900. if (light.type === "ambient") {
  72901. var ambienLight = light[light.type];
  72902. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72903. hemiLight.name = node.name;
  72904. if (ambienLight.color) {
  72905. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  72906. }
  72907. lastNode = hemiLight;
  72908. }
  72909. else if (light.type === "directional") {
  72910. var directionalLight = light[light.type];
  72911. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72912. dirLight.name = node.name;
  72913. if (directionalLight.color) {
  72914. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  72915. }
  72916. lastNode = dirLight;
  72917. }
  72918. else if (light.type === "point") {
  72919. var pointLight = light[light.type];
  72920. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72921. ptLight.name = node.name;
  72922. if (pointLight.color) {
  72923. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  72924. }
  72925. lastNode = ptLight;
  72926. }
  72927. else if (light.type === "spot") {
  72928. var spotLight = light[light.type];
  72929. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  72930. spLight.name = node.name;
  72931. if (spotLight.color) {
  72932. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  72933. }
  72934. if (spotLight.fallOfAngle) {
  72935. spLight.angle = spotLight.fallOfAngle;
  72936. }
  72937. if (spotLight.fallOffExponent) {
  72938. spLight.exponent = spotLight.fallOffExponent;
  72939. }
  72940. lastNode = spLight;
  72941. }
  72942. }
  72943. }
  72944. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  72945. var camera = gltfRuntime.cameras[node.camera];
  72946. if (camera) {
  72947. if (camera.type === "orthographic") {
  72948. var orthographicCamera = camera[camera.type];
  72949. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72950. orthoCamera.name = node.name;
  72951. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  72952. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  72953. lastNode = orthoCamera;
  72954. }
  72955. else if (camera.type === "perspective") {
  72956. var perspectiveCamera = camera[camera.type];
  72957. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72958. persCamera.name = node.name;
  72959. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  72960. if (!perspectiveCamera.aspectRatio) {
  72961. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  72962. }
  72963. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  72964. persCamera.maxZ = perspectiveCamera.zfar;
  72965. persCamera.minZ = perspectiveCamera.znear;
  72966. }
  72967. lastNode = persCamera;
  72968. }
  72969. }
  72970. }
  72971. // Empty node
  72972. if (!node.jointName) {
  72973. if (node.babylonNode) {
  72974. return node.babylonNode;
  72975. }
  72976. else if (lastNode === null) {
  72977. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  72978. node.babylonNode = dummy;
  72979. lastNode = dummy;
  72980. }
  72981. }
  72982. if (lastNode !== null) {
  72983. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  72984. configureNodeFromMatrix(lastNode, node, parent);
  72985. }
  72986. else {
  72987. var translation = node.translation || [0, 0, 0];
  72988. var rotation = node.rotation || [0, 0, 0, 1];
  72989. var scale = node.scale || [1, 1, 1];
  72990. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  72991. }
  72992. lastNode.updateCache(true);
  72993. node.babylonNode = lastNode;
  72994. }
  72995. return lastNode;
  72996. };
  72997. /**
  72998. * Traverses nodes and creates them
  72999. */
  73000. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  73001. var node = gltfRuntime.nodes[id];
  73002. var newNode = null;
  73003. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  73004. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  73005. meshIncluded = true;
  73006. }
  73007. else {
  73008. meshIncluded = false;
  73009. }
  73010. }
  73011. else {
  73012. meshIncluded = true;
  73013. }
  73014. if (!node.jointName && meshIncluded) {
  73015. newNode = importNode(gltfRuntime, node, id, parent);
  73016. if (newNode !== null) {
  73017. newNode.id = id;
  73018. newNode.parent = parent;
  73019. }
  73020. }
  73021. if (node.children) {
  73022. for (var i = 0; i < node.children.length; i++) {
  73023. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  73024. }
  73025. }
  73026. };
  73027. /**
  73028. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  73029. */
  73030. var postLoad = function (gltfRuntime) {
  73031. // Nodes
  73032. var currentScene = gltfRuntime.currentScene;
  73033. if (currentScene) {
  73034. for (var i = 0; i < currentScene.nodes.length; i++) {
  73035. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73036. }
  73037. }
  73038. else {
  73039. for (var thing in gltfRuntime.scenes) {
  73040. currentScene = gltfRuntime.scenes[thing];
  73041. for (var i = 0; i < currentScene.nodes.length; i++) {
  73042. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73043. }
  73044. }
  73045. }
  73046. // Set animations
  73047. loadAnimations(gltfRuntime);
  73048. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  73049. var skeleton = gltfRuntime.scene.skeletons[i];
  73050. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  73051. }
  73052. };
  73053. /**
  73054. * onBind shaderrs callback to set uniforms and matrices
  73055. */
  73056. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  73057. var materialValues = material.values || technique.parameters;
  73058. for (var unif in unTreatedUniforms) {
  73059. var uniform = unTreatedUniforms[unif];
  73060. var type = uniform.type;
  73061. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  73062. if (uniform.semantic && !uniform.source && !uniform.node) {
  73063. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  73064. }
  73065. else if (uniform.semantic && (uniform.source || uniform.node)) {
  73066. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  73067. if (source === null) {
  73068. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  73069. }
  73070. if (source === null) {
  73071. continue;
  73072. }
  73073. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  73074. }
  73075. }
  73076. else {
  73077. var value = materialValues[technique.uniforms[unif]];
  73078. if (!value) {
  73079. continue;
  73080. }
  73081. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73082. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  73083. if (texture === null || texture === undefined) {
  73084. continue;
  73085. }
  73086. shaderMaterial.getEffect().setTexture(unif, texture);
  73087. }
  73088. else {
  73089. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  73090. }
  73091. }
  73092. }
  73093. onSuccess(shaderMaterial);
  73094. };
  73095. /**
  73096. * Prepare uniforms to send the only one time
  73097. * Loads the appropriate textures
  73098. */
  73099. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  73100. var materialValues = material.values || technique.parameters;
  73101. var techniqueUniforms = technique.uniforms;
  73102. /**
  73103. * Prepare values here (not matrices)
  73104. */
  73105. for (var unif in unTreatedUniforms) {
  73106. var uniform = unTreatedUniforms[unif];
  73107. var type = uniform.type;
  73108. var value = materialValues[techniqueUniforms[unif]];
  73109. if (value === undefined) {
  73110. // In case the value is the same for all materials
  73111. value = uniform.value;
  73112. }
  73113. if (!value) {
  73114. continue;
  73115. }
  73116. var onLoadTexture = function (uniformName) {
  73117. return function (texture) {
  73118. if (uniform.value) {
  73119. // Static uniform
  73120. shaderMaterial.setTexture(uniformName, texture);
  73121. delete unTreatedUniforms[uniformName];
  73122. }
  73123. };
  73124. };
  73125. // Texture (sampler2D)
  73126. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73127. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  73128. }
  73129. else {
  73130. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  73131. // Static uniform
  73132. delete unTreatedUniforms[unif];
  73133. }
  73134. }
  73135. }
  73136. };
  73137. /**
  73138. * Shader compilation failed
  73139. */
  73140. var onShaderCompileError = function (program, shaderMaterial, onError) {
  73141. return function (effect, error) {
  73142. shaderMaterial.dispose(true);
  73143. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  73144. };
  73145. };
  73146. /**
  73147. * Shader compilation success
  73148. */
  73149. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  73150. return function (_) {
  73151. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  73152. shaderMaterial.onBind = function (mesh) {
  73153. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  73154. };
  73155. };
  73156. };
  73157. /**
  73158. * Returns the appropriate uniform if already handled by babylon
  73159. */
  73160. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  73161. for (var unif in technique.uniforms) {
  73162. var uniform = technique.uniforms[unif];
  73163. var uniformParameter = technique.parameters[uniform];
  73164. if (tokenizer.currentIdentifier === unif) {
  73165. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  73166. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73167. if (transformIndex !== -1) {
  73168. delete unTreatedUniforms[unif];
  73169. return babylonTransforms[transformIndex];
  73170. }
  73171. }
  73172. }
  73173. }
  73174. return tokenizer.currentIdentifier;
  73175. };
  73176. /**
  73177. * All shaders loaded. Create materials one by one
  73178. */
  73179. var importMaterials = function (gltfRuntime) {
  73180. // Create materials
  73181. for (var mat in gltfRuntime.materials) {
  73182. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  73183. }
  73184. };
  73185. /**
  73186. * Implementation of the base glTF spec
  73187. */
  73188. var GLTFLoaderBase = (function () {
  73189. function GLTFLoaderBase() {
  73190. }
  73191. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  73192. var gltfRuntime = {
  73193. extensions: {},
  73194. accessors: {},
  73195. buffers: {},
  73196. bufferViews: {},
  73197. meshes: {},
  73198. lights: {},
  73199. cameras: {},
  73200. nodes: {},
  73201. images: {},
  73202. textures: {},
  73203. shaders: {},
  73204. programs: {},
  73205. samplers: {},
  73206. techniques: {},
  73207. materials: {},
  73208. animations: {},
  73209. skins: {},
  73210. extensionsUsed: [],
  73211. scenes: {},
  73212. buffersCount: 0,
  73213. shaderscount: 0,
  73214. scene: scene,
  73215. rootUrl: rootUrl,
  73216. loadedBufferCount: 0,
  73217. loadedBufferViews: {},
  73218. loadedShaderCount: 0,
  73219. importOnlyMeshes: false,
  73220. dummyNodes: []
  73221. };
  73222. // Parse
  73223. if (parsedData.extensions) {
  73224. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  73225. }
  73226. if (parsedData.extensionsUsed) {
  73227. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  73228. }
  73229. if (parsedData.buffers) {
  73230. parseBuffers(parsedData.buffers, gltfRuntime);
  73231. }
  73232. if (parsedData.bufferViews) {
  73233. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  73234. }
  73235. if (parsedData.accessors) {
  73236. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  73237. }
  73238. if (parsedData.meshes) {
  73239. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  73240. }
  73241. if (parsedData.lights) {
  73242. parseObject(parsedData.lights, "lights", gltfRuntime);
  73243. }
  73244. if (parsedData.cameras) {
  73245. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  73246. }
  73247. if (parsedData.nodes) {
  73248. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  73249. }
  73250. if (parsedData.images) {
  73251. parseObject(parsedData.images, "images", gltfRuntime);
  73252. }
  73253. if (parsedData.textures) {
  73254. parseObject(parsedData.textures, "textures", gltfRuntime);
  73255. }
  73256. if (parsedData.shaders) {
  73257. parseShaders(parsedData.shaders, gltfRuntime);
  73258. }
  73259. if (parsedData.programs) {
  73260. parseObject(parsedData.programs, "programs", gltfRuntime);
  73261. }
  73262. if (parsedData.samplers) {
  73263. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  73264. }
  73265. if (parsedData.techniques) {
  73266. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  73267. }
  73268. if (parsedData.materials) {
  73269. parseObject(parsedData.materials, "materials", gltfRuntime);
  73270. }
  73271. if (parsedData.animations) {
  73272. parseObject(parsedData.animations, "animations", gltfRuntime);
  73273. }
  73274. if (parsedData.skins) {
  73275. parseObject(parsedData.skins, "skins", gltfRuntime);
  73276. }
  73277. if (parsedData.scenes) {
  73278. gltfRuntime.scenes = parsedData.scenes;
  73279. }
  73280. if (parsedData.scene && parsedData.scenes) {
  73281. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  73282. }
  73283. return gltfRuntime;
  73284. };
  73285. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73286. var buffer = gltfRuntime.buffers[id];
  73287. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  73288. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  73289. }
  73290. else {
  73291. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  73292. onError(request.status + " " + request.statusText);
  73293. });
  73294. }
  73295. };
  73296. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73297. var texture = gltfRuntime.textures[id];
  73298. if (!texture || !texture.source) {
  73299. onError(null);
  73300. return;
  73301. }
  73302. if (texture.babylonTexture) {
  73303. onSuccess(null);
  73304. return;
  73305. }
  73306. var source = gltfRuntime.images[texture.source];
  73307. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  73308. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  73309. }
  73310. else {
  73311. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  73312. onError(request.status + " " + request.statusText);
  73313. });
  73314. }
  73315. };
  73316. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73317. var texture = gltfRuntime.textures[id];
  73318. if (texture.babylonTexture) {
  73319. onSuccess(texture.babylonTexture);
  73320. return;
  73321. }
  73322. var sampler = gltfRuntime.samplers[texture.sampler];
  73323. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  73324. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  73325. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  73326. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  73327. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  73328. var blob = new Blob([buffer]);
  73329. var blobURL = URL.createObjectURL(blob);
  73330. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  73331. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  73332. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  73333. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  73334. newTexture.name = id;
  73335. texture.babylonTexture = newTexture;
  73336. onSuccess(newTexture);
  73337. };
  73338. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73339. var shader = gltfRuntime.shaders[id];
  73340. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  73341. var shaderString = atob(shader.uri.split(",")[1]);
  73342. onSuccess(shaderString);
  73343. }
  73344. else {
  73345. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  73346. onError(request.status + " " + request.statusText);
  73347. });
  73348. }
  73349. };
  73350. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73351. var material = gltfRuntime.materials[id];
  73352. var technique = gltfRuntime.techniques[material.technique];
  73353. if (!technique) {
  73354. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  73355. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  73356. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73357. onSuccess(defaultMaterial);
  73358. return;
  73359. }
  73360. var program = gltfRuntime.programs[technique.program];
  73361. var states = technique.states;
  73362. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  73363. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  73364. var newVertexShader = "";
  73365. var newPixelShader = "";
  73366. var vertexTokenizer = new Tokenizer(vertexShader);
  73367. var pixelTokenizer = new Tokenizer(pixelShader);
  73368. var unTreatedUniforms = {};
  73369. var uniforms = [];
  73370. var attributes = [];
  73371. var samplers = [];
  73372. // Fill uniform, sampler2D and attributes
  73373. for (var unif in technique.uniforms) {
  73374. var uniform = technique.uniforms[unif];
  73375. var uniformParameter = technique.parameters[uniform];
  73376. unTreatedUniforms[unif] = uniformParameter;
  73377. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  73378. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73379. if (transformIndex !== -1) {
  73380. uniforms.push(babylonTransforms[transformIndex]);
  73381. delete unTreatedUniforms[unif];
  73382. }
  73383. else {
  73384. uniforms.push(unif);
  73385. }
  73386. }
  73387. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  73388. samplers.push(unif);
  73389. }
  73390. else {
  73391. uniforms.push(unif);
  73392. }
  73393. }
  73394. for (var attr in technique.attributes) {
  73395. var attribute = technique.attributes[attr];
  73396. var attributeParameter = technique.parameters[attribute];
  73397. if (attributeParameter.semantic) {
  73398. attributes.push(getAttribute(attributeParameter));
  73399. }
  73400. }
  73401. // Configure vertex shader
  73402. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  73403. var tokenType = vertexTokenizer.currentToken;
  73404. if (tokenType !== ETokenType.IDENTIFIER) {
  73405. newVertexShader += vertexTokenizer.currentString;
  73406. continue;
  73407. }
  73408. var foundAttribute = false;
  73409. for (var attr in technique.attributes) {
  73410. var attribute = technique.attributes[attr];
  73411. var attributeParameter = technique.parameters[attribute];
  73412. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  73413. newVertexShader += getAttribute(attributeParameter);
  73414. foundAttribute = true;
  73415. break;
  73416. }
  73417. }
  73418. if (foundAttribute) {
  73419. continue;
  73420. }
  73421. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  73422. }
  73423. // Configure pixel shader
  73424. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  73425. var tokenType = pixelTokenizer.currentToken;
  73426. if (tokenType !== ETokenType.IDENTIFIER) {
  73427. newPixelShader += pixelTokenizer.currentString;
  73428. continue;
  73429. }
  73430. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  73431. }
  73432. // Create shader material
  73433. var shaderPath = {
  73434. vertex: program.vertexShader + id,
  73435. fragment: program.fragmentShader + id
  73436. };
  73437. var options = {
  73438. attributes: attributes,
  73439. uniforms: uniforms,
  73440. samplers: samplers,
  73441. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  73442. };
  73443. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  73444. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  73445. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  73446. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  73447. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  73448. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73449. if (states && states.functions) {
  73450. var functions = states.functions;
  73451. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  73452. shaderMaterial.backFaceCulling = false;
  73453. }
  73454. var blendFunc = functions.blendFuncSeparate;
  73455. if (blendFunc) {
  73456. 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) {
  73457. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  73458. }
  73459. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73460. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73461. }
  73462. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73463. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  73464. }
  73465. 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) {
  73466. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  73467. }
  73468. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  73469. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  73470. }
  73471. 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) {
  73472. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  73473. }
  73474. }
  73475. }
  73476. };
  73477. return GLTFLoaderBase;
  73478. }());
  73479. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  73480. /**
  73481. * glTF V1 Loader
  73482. */
  73483. var GLTFLoader = (function () {
  73484. function GLTFLoader() {
  73485. }
  73486. GLTFLoader.RegisterExtension = function (extension) {
  73487. if (GLTFLoader.Extensions[extension.name]) {
  73488. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  73489. return;
  73490. }
  73491. GLTFLoader.Extensions[extension.name] = extension;
  73492. };
  73493. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  73494. var _this = this;
  73495. scene.useRightHandedSystem = true;
  73496. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73497. gltfRuntime.importOnlyMeshes = true;
  73498. if (meshesNames === "") {
  73499. gltfRuntime.importMeshesNames = [];
  73500. }
  73501. else if (typeof meshesNames === "string") {
  73502. gltfRuntime.importMeshesNames = [meshesNames];
  73503. }
  73504. else if (meshesNames && !(meshesNames instanceof Array)) {
  73505. gltfRuntime.importMeshesNames = [meshesNames];
  73506. }
  73507. else {
  73508. gltfRuntime.importMeshesNames = [];
  73509. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  73510. }
  73511. // Create nodes
  73512. _this._createNodes(gltfRuntime);
  73513. var meshes = [];
  73514. var skeletons = [];
  73515. // Fill arrays of meshes and skeletons
  73516. for (var nde in gltfRuntime.nodes) {
  73517. var node = gltfRuntime.nodes[nde];
  73518. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  73519. meshes.push(node.babylonNode);
  73520. }
  73521. }
  73522. for (var skl in gltfRuntime.skins) {
  73523. var skin = gltfRuntime.skins[skl];
  73524. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  73525. skeletons.push(skin.babylonSkeleton);
  73526. }
  73527. }
  73528. // Load buffers, shaders, materials, etc.
  73529. _this._loadBuffersAsync(gltfRuntime, function () {
  73530. _this._loadShadersAsync(gltfRuntime, function () {
  73531. importMaterials(gltfRuntime);
  73532. postLoad(gltfRuntime);
  73533. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73534. onSuccess(meshes, null, skeletons);
  73535. }
  73536. });
  73537. }, onProgress);
  73538. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73539. onSuccess(meshes, null, skeletons);
  73540. }
  73541. }, onError);
  73542. return true;
  73543. };
  73544. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  73545. var _this = this;
  73546. scene.useRightHandedSystem = true;
  73547. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73548. // Load runtime extensios
  73549. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  73550. // Create nodes
  73551. _this._createNodes(gltfRuntime);
  73552. // Load buffers, shaders, materials, etc.
  73553. _this._loadBuffersAsync(gltfRuntime, function () {
  73554. _this._loadShadersAsync(gltfRuntime, function () {
  73555. importMaterials(gltfRuntime);
  73556. postLoad(gltfRuntime);
  73557. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  73558. onSuccess();
  73559. }
  73560. });
  73561. });
  73562. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  73563. onSuccess();
  73564. }
  73565. }, onError);
  73566. }, onError);
  73567. };
  73568. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  73569. var hasShaders = false;
  73570. var processShader = function (sha, shader) {
  73571. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  73572. gltfRuntime.loadedShaderCount++;
  73573. if (shaderString) {
  73574. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  73575. }
  73576. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  73577. onload();
  73578. }
  73579. }, function () {
  73580. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  73581. });
  73582. };
  73583. for (var sha in gltfRuntime.shaders) {
  73584. hasShaders = true;
  73585. var shader = gltfRuntime.shaders[sha];
  73586. if (shader) {
  73587. processShader.bind(this, sha, shader)();
  73588. }
  73589. else {
  73590. BABYLON.Tools.Error("No shader named: " + sha);
  73591. }
  73592. }
  73593. if (!hasShaders) {
  73594. onload();
  73595. }
  73596. };
  73597. ;
  73598. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  73599. var hasBuffers = false;
  73600. var processBuffer = function (buf, buffer) {
  73601. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  73602. gltfRuntime.loadedBufferCount++;
  73603. if (bufferView) {
  73604. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  73605. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  73606. }
  73607. gltfRuntime.loadedBufferViews[buf] = bufferView;
  73608. }
  73609. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  73610. onLoad();
  73611. }
  73612. }, function () {
  73613. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  73614. });
  73615. };
  73616. for (var buf in gltfRuntime.buffers) {
  73617. hasBuffers = true;
  73618. var buffer = gltfRuntime.buffers[buf];
  73619. if (buffer) {
  73620. processBuffer.bind(this, buf, buffer)();
  73621. }
  73622. else {
  73623. BABYLON.Tools.Error("No buffer named: " + buf);
  73624. }
  73625. }
  73626. if (!hasBuffers) {
  73627. onLoad();
  73628. }
  73629. };
  73630. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  73631. var currentScene = gltfRuntime.currentScene;
  73632. if (currentScene) {
  73633. // Only one scene even if multiple scenes are defined
  73634. for (var i = 0; i < currentScene.nodes.length; i++) {
  73635. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73636. }
  73637. }
  73638. else {
  73639. // Load all scenes
  73640. for (var thing in gltfRuntime.scenes) {
  73641. currentScene = gltfRuntime.scenes[thing];
  73642. for (var i = 0; i < currentScene.nodes.length; i++) {
  73643. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73644. }
  73645. }
  73646. }
  73647. };
  73648. GLTFLoader.Extensions = {};
  73649. return GLTFLoader;
  73650. }());
  73651. GLTF1.GLTFLoader = GLTFLoader;
  73652. ;
  73653. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  73654. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73655. })(BABYLON || (BABYLON = {}));
  73656. //# sourceMappingURL=babylon.glTFLoader.js.map
  73657. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73658. var BABYLON;
  73659. (function (BABYLON) {
  73660. var GLTF1;
  73661. (function (GLTF1) {
  73662. /**
  73663. * Utils functions for GLTF
  73664. */
  73665. var GLTFUtils = (function () {
  73666. function GLTFUtils() {
  73667. }
  73668. /**
  73669. * Sets the given "parameter" matrix
  73670. * @param scene: the {BABYLON.Scene} object
  73671. * @param source: the source node where to pick the matrix
  73672. * @param parameter: the GLTF technique parameter
  73673. * @param uniformName: the name of the shader's uniform
  73674. * @param shaderMaterial: the shader material
  73675. */
  73676. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  73677. var mat = null;
  73678. if (parameter.semantic === "MODEL") {
  73679. mat = source.getWorldMatrix();
  73680. }
  73681. else if (parameter.semantic === "PROJECTION") {
  73682. mat = scene.getProjectionMatrix();
  73683. }
  73684. else if (parameter.semantic === "VIEW") {
  73685. mat = scene.getViewMatrix();
  73686. }
  73687. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  73688. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  73689. }
  73690. else if (parameter.semantic === "MODELVIEW") {
  73691. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  73692. }
  73693. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  73694. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  73695. }
  73696. else if (parameter.semantic === "MODELINVERSE") {
  73697. mat = source.getWorldMatrix().invert();
  73698. }
  73699. else if (parameter.semantic === "VIEWINVERSE") {
  73700. mat = scene.getViewMatrix().invert();
  73701. }
  73702. else if (parameter.semantic === "PROJECTIONINVERSE") {
  73703. mat = scene.getProjectionMatrix().invert();
  73704. }
  73705. else if (parameter.semantic === "MODELVIEWINVERSE") {
  73706. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  73707. }
  73708. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  73709. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  73710. }
  73711. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  73712. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  73713. }
  73714. else {
  73715. debugger;
  73716. }
  73717. switch (parameter.type) {
  73718. case GLTF1.EParameterType.FLOAT_MAT2:
  73719. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  73720. break;
  73721. case GLTF1.EParameterType.FLOAT_MAT3:
  73722. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  73723. break;
  73724. case GLTF1.EParameterType.FLOAT_MAT4:
  73725. shaderMaterial.setMatrix(uniformName, mat);
  73726. break;
  73727. default: break;
  73728. }
  73729. };
  73730. /**
  73731. * Sets the given "parameter" matrix
  73732. * @param shaderMaterial: the shader material
  73733. * @param uniform: the name of the shader's uniform
  73734. * @param value: the value of the uniform
  73735. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  73736. */
  73737. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  73738. switch (type) {
  73739. case GLTF1.EParameterType.FLOAT:
  73740. shaderMaterial.setFloat(uniform, value);
  73741. return true;
  73742. case GLTF1.EParameterType.FLOAT_VEC2:
  73743. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  73744. return true;
  73745. case GLTF1.EParameterType.FLOAT_VEC3:
  73746. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  73747. return true;
  73748. case GLTF1.EParameterType.FLOAT_VEC4:
  73749. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  73750. return true;
  73751. default: return false;
  73752. }
  73753. };
  73754. /**
  73755. * If the uri is a base64 string
  73756. * @param uri: the uri to test
  73757. */
  73758. GLTFUtils.IsBase64 = function (uri) {
  73759. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  73760. };
  73761. /**
  73762. * Decode the base64 uri
  73763. * @param uri: the uri to decode
  73764. */
  73765. GLTFUtils.DecodeBase64 = function (uri) {
  73766. var decodedString = atob(uri.split(",")[1]);
  73767. var bufferLength = decodedString.length;
  73768. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  73769. for (var i = 0; i < bufferLength; i++) {
  73770. bufferView[i] = decodedString.charCodeAt(i);
  73771. }
  73772. return bufferView.buffer;
  73773. };
  73774. /**
  73775. * Returns the wrap mode of the texture
  73776. * @param mode: the mode value
  73777. */
  73778. GLTFUtils.GetWrapMode = function (mode) {
  73779. switch (mode) {
  73780. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  73781. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  73782. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  73783. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  73784. }
  73785. };
  73786. /**
  73787. * Returns the byte stride giving an accessor
  73788. * @param accessor: the GLTF accessor objet
  73789. */
  73790. GLTFUtils.GetByteStrideFromType = function (accessor) {
  73791. // Needs this function since "byteStride" isn't requiered in glTF format
  73792. var type = accessor.type;
  73793. switch (type) {
  73794. case "VEC2": return 2;
  73795. case "VEC3": return 3;
  73796. case "VEC4": return 4;
  73797. case "MAT2": return 4;
  73798. case "MAT3": return 9;
  73799. case "MAT4": return 16;
  73800. default: return 1;
  73801. }
  73802. };
  73803. /**
  73804. * Returns the texture filter mode giving a mode value
  73805. * @param mode: the filter mode value
  73806. */
  73807. GLTFUtils.GetTextureFilterMode = function (mode) {
  73808. switch (mode) {
  73809. case GLTF1.ETextureFilterType.LINEAR:
  73810. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  73811. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  73812. case GLTF1.ETextureFilterType.NEAREST:
  73813. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73814. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  73815. }
  73816. };
  73817. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  73818. var byteOffset = bufferView.byteOffset + byteOffset;
  73819. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  73820. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  73821. throw new Error("Buffer access is out of range");
  73822. }
  73823. var buffer = loadedBufferView.buffer;
  73824. byteOffset += loadedBufferView.byteOffset;
  73825. switch (componentType) {
  73826. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  73827. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  73828. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  73829. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  73830. default: return new Float32Array(buffer, byteOffset, byteLength);
  73831. }
  73832. };
  73833. /**
  73834. * Returns a buffer from its accessor
  73835. * @param gltfRuntime: the GLTF runtime
  73836. * @param accessor: the GLTF accessor
  73837. */
  73838. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  73839. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  73840. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  73841. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  73842. };
  73843. /**
  73844. * Decodes a buffer view into a string
  73845. * @param view: the buffer view
  73846. */
  73847. GLTFUtils.DecodeBufferToText = function (view) {
  73848. var result = "";
  73849. var length = view.byteLength;
  73850. for (var i = 0; i < length; ++i) {
  73851. result += String.fromCharCode(view[i]);
  73852. }
  73853. return result;
  73854. };
  73855. /**
  73856. * Returns the default material of gltf. Related to
  73857. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  73858. * @param scene: the Babylon.js scene
  73859. */
  73860. GLTFUtils.GetDefaultMaterial = function (scene) {
  73861. if (!GLTFUtils._DefaultMaterial) {
  73862. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  73863. "precision highp float;",
  73864. "",
  73865. "uniform mat4 worldView;",
  73866. "uniform mat4 projection;",
  73867. "",
  73868. "attribute vec3 position;",
  73869. "",
  73870. "void main(void)",
  73871. "{",
  73872. " gl_Position = projection * worldView * vec4(position, 1.0);",
  73873. "}"
  73874. ].join("\n");
  73875. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  73876. "precision highp float;",
  73877. "",
  73878. "uniform vec4 u_emission;",
  73879. "",
  73880. "void main(void)",
  73881. "{",
  73882. " gl_FragColor = u_emission;",
  73883. "}"
  73884. ].join("\n");
  73885. var shaderPath = {
  73886. vertex: "GLTFDefaultMaterial",
  73887. fragment: "GLTFDefaultMaterial"
  73888. };
  73889. var options = {
  73890. attributes: ["position"],
  73891. uniforms: ["worldView", "projection", "u_emission"],
  73892. samplers: [],
  73893. needAlphaBlending: false
  73894. };
  73895. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  73896. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  73897. }
  73898. return GLTFUtils._DefaultMaterial;
  73899. };
  73900. // The GLTF default material
  73901. GLTFUtils._DefaultMaterial = null;
  73902. return GLTFUtils;
  73903. }());
  73904. GLTF1.GLTFUtils = GLTFUtils;
  73905. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73906. })(BABYLON || (BABYLON = {}));
  73907. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  73908. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73909. var BABYLON;
  73910. (function (BABYLON) {
  73911. var GLTF1;
  73912. (function (GLTF1) {
  73913. var GLTFLoaderExtension = (function () {
  73914. function GLTFLoaderExtension(name) {
  73915. this._name = name;
  73916. }
  73917. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  73918. get: function () {
  73919. return this._name;
  73920. },
  73921. enumerable: true,
  73922. configurable: true
  73923. });
  73924. /**
  73925. * Defines an override for loading the runtime
  73926. * Return true to stop further extensions from loading the runtime
  73927. */
  73928. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  73929. return false;
  73930. };
  73931. /**
  73932. * Defines an onverride for creating gltf runtime
  73933. * Return true to stop further extensions from creating the runtime
  73934. */
  73935. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  73936. return false;
  73937. };
  73938. /**
  73939. * Defines an override for loading buffers
  73940. * Return true to stop further extensions from loading this buffer
  73941. */
  73942. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73943. return false;
  73944. };
  73945. /**
  73946. * Defines an override for loading texture buffers
  73947. * Return true to stop further extensions from loading this texture data
  73948. */
  73949. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73950. return false;
  73951. };
  73952. /**
  73953. * Defines an override for creating textures
  73954. * Return true to stop further extensions from loading this texture
  73955. */
  73956. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73957. return false;
  73958. };
  73959. /**
  73960. * Defines an override for loading shader strings
  73961. * Return true to stop further extensions from loading this shader data
  73962. */
  73963. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73964. return false;
  73965. };
  73966. /**
  73967. * Defines an override for loading materials
  73968. * Return true to stop further extensions from loading this material
  73969. */
  73970. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73971. return false;
  73972. };
  73973. // ---------
  73974. // Utilities
  73975. // ---------
  73976. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  73977. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73978. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  73979. }, function () {
  73980. setTimeout(function () {
  73981. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  73982. });
  73983. });
  73984. };
  73985. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  73986. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73987. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  73988. }, function () {
  73989. setTimeout(function () {
  73990. onSuccess();
  73991. });
  73992. });
  73993. };
  73994. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73995. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73996. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  73997. }, function () {
  73998. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  73999. });
  74000. };
  74001. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  74002. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  74003. };
  74004. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74005. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74006. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74007. }, function () {
  74008. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74009. });
  74010. };
  74011. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74012. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74013. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74014. }, function () {
  74015. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74016. });
  74017. };
  74018. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74019. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74020. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74021. }, function () {
  74022. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74023. });
  74024. };
  74025. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74026. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74027. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74028. }, function () {
  74029. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74030. });
  74031. };
  74032. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  74033. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  74034. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  74035. if (func(loaderExtension)) {
  74036. return;
  74037. }
  74038. }
  74039. defaultFunc();
  74040. };
  74041. return GLTFLoaderExtension;
  74042. }());
  74043. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  74044. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74045. })(BABYLON || (BABYLON = {}));
  74046. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  74047. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74048. var BABYLON;
  74049. (function (BABYLON) {
  74050. var GLTF1;
  74051. (function (GLTF1) {
  74052. var BinaryExtensionBufferName = "binary_glTF";
  74053. var EContentFormat;
  74054. (function (EContentFormat) {
  74055. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  74056. })(EContentFormat || (EContentFormat = {}));
  74057. ;
  74058. ;
  74059. ;
  74060. var GLTFBinaryExtension = (function (_super) {
  74061. __extends(GLTFBinaryExtension, _super);
  74062. function GLTFBinaryExtension() {
  74063. return _super.call(this, "KHR_binary_glTF") || this;
  74064. }
  74065. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74066. var extensionsUsed = data.json.extensionsUsed;
  74067. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  74068. return false;
  74069. }
  74070. this._bin = data.bin;
  74071. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74072. return true;
  74073. };
  74074. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74075. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  74076. return false;
  74077. }
  74078. if (id !== BinaryExtensionBufferName) {
  74079. return false;
  74080. }
  74081. onSuccess(this._bin);
  74082. return true;
  74083. };
  74084. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74085. var texture = gltfRuntime.textures[id];
  74086. var source = gltfRuntime.images[texture.source];
  74087. if (!source.extensions || !(this.name in source.extensions)) {
  74088. return false;
  74089. }
  74090. var sourceExt = source.extensions[this.name];
  74091. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  74092. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74093. onSuccess(buffer);
  74094. return true;
  74095. };
  74096. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74097. var shader = gltfRuntime.shaders[id];
  74098. if (!shader.extensions || !(this.name in shader.extensions)) {
  74099. return false;
  74100. }
  74101. var binaryExtensionShader = shader.extensions[this.name];
  74102. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  74103. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74104. setTimeout(function () {
  74105. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  74106. onSuccess(shaderString);
  74107. });
  74108. return true;
  74109. };
  74110. return GLTFBinaryExtension;
  74111. }(GLTF1.GLTFLoaderExtension));
  74112. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  74113. var BinaryReader = (function () {
  74114. function BinaryReader(arrayBuffer) {
  74115. this._arrayBuffer = arrayBuffer;
  74116. this._dataView = new DataView(arrayBuffer);
  74117. this._byteOffset = 0;
  74118. }
  74119. BinaryReader.prototype.getUint32 = function () {
  74120. var value = this._dataView.getUint32(this._byteOffset, true);
  74121. this._byteOffset += 4;
  74122. return value;
  74123. };
  74124. BinaryReader.prototype.getUint8Array = function (length) {
  74125. if (!length) {
  74126. length = this._arrayBuffer.byteLength - this._byteOffset;
  74127. }
  74128. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  74129. this._byteOffset += length;
  74130. return value;
  74131. };
  74132. return BinaryReader;
  74133. }());
  74134. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  74135. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74136. })(BABYLON || (BABYLON = {}));
  74137. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  74138. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74139. var BABYLON;
  74140. (function (BABYLON) {
  74141. var GLTF1;
  74142. (function (GLTF1) {
  74143. ;
  74144. ;
  74145. ;
  74146. var GLTFMaterialsCommonExtension = (function (_super) {
  74147. __extends(GLTFMaterialsCommonExtension, _super);
  74148. function GLTFMaterialsCommonExtension() {
  74149. return _super.call(this, "KHR_materials_common") || this;
  74150. }
  74151. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74152. if (!gltfRuntime.extensions)
  74153. return false;
  74154. var extension = gltfRuntime.extensions[this.name];
  74155. if (!extension)
  74156. return false;
  74157. // Create lights
  74158. var lights = extension.lights;
  74159. if (lights) {
  74160. for (var thing in lights) {
  74161. var light = lights[thing];
  74162. switch (light.type) {
  74163. case "ambient":
  74164. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  74165. var ambient = light.ambient;
  74166. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  74167. break;
  74168. case "point":
  74169. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  74170. var point = light.point;
  74171. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  74172. break;
  74173. case "directional":
  74174. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  74175. var directional = light.directional;
  74176. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  74177. break;
  74178. case "spot":
  74179. var spot = light.spot;
  74180. 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);
  74181. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  74182. break;
  74183. default:
  74184. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  74185. break;
  74186. }
  74187. }
  74188. }
  74189. return false;
  74190. };
  74191. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74192. var material = gltfRuntime.materials[id];
  74193. if (!material || !material.extensions)
  74194. return false;
  74195. var extension = material.extensions[this.name];
  74196. if (!extension)
  74197. return false;
  74198. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74199. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74200. if (extension.technique === "CONSTANT") {
  74201. standardMaterial.disableLighting = true;
  74202. }
  74203. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  74204. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  74205. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  74206. // Ambient
  74207. if (typeof extension.values.ambient === "string") {
  74208. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  74209. }
  74210. else {
  74211. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  74212. }
  74213. // Diffuse
  74214. if (typeof extension.values.diffuse === "string") {
  74215. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  74216. }
  74217. else {
  74218. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  74219. }
  74220. // Emission
  74221. if (typeof extension.values.emission === "string") {
  74222. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  74223. }
  74224. else {
  74225. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  74226. }
  74227. // Specular
  74228. if (typeof extension.values.specular === "string") {
  74229. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  74230. }
  74231. else {
  74232. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  74233. }
  74234. return true;
  74235. };
  74236. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  74237. // Create buffer from texture url
  74238. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  74239. // Create texture from buffer
  74240. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  74241. }, onError);
  74242. };
  74243. return GLTFMaterialsCommonExtension;
  74244. }(GLTF1.GLTFLoaderExtension));
  74245. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  74246. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  74247. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74248. })(BABYLON || (BABYLON = {}));
  74249. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  74250. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74251. var BABYLON;
  74252. (function (BABYLON) {
  74253. var GLTF2;
  74254. (function (GLTF2) {
  74255. /**
  74256. * Enums
  74257. */
  74258. var EComponentType;
  74259. (function (EComponentType) {
  74260. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  74261. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  74262. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  74263. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  74264. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  74265. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  74266. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  74267. var EMeshPrimitiveMode;
  74268. (function (EMeshPrimitiveMode) {
  74269. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  74270. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  74271. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  74272. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  74273. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  74274. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  74275. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  74276. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  74277. var ETextureMagFilter;
  74278. (function (ETextureMagFilter) {
  74279. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  74280. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  74281. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  74282. var ETextureMinFilter;
  74283. (function (ETextureMinFilter) {
  74284. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  74285. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  74286. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  74287. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  74288. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  74289. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  74290. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  74291. var ETextureWrapMode;
  74292. (function (ETextureWrapMode) {
  74293. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  74294. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  74295. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  74296. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  74297. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74298. })(BABYLON || (BABYLON = {}));
  74299. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  74300. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74301. var BABYLON;
  74302. (function (BABYLON) {
  74303. var GLTF2;
  74304. (function (GLTF2) {
  74305. var GLTFLoader = (function () {
  74306. function GLTFLoader(parent) {
  74307. this._renderReady = false;
  74308. this._disposed = false;
  74309. this._blockPendingTracking = false;
  74310. // Observable with boolean indicating success or error.
  74311. this._renderReadyObservable = new BABYLON.Observable();
  74312. // Count of pending work that needs to complete before the asset is rendered.
  74313. this._renderPendingCount = 0;
  74314. // Count of pending work that needs to complete before the loader is cleared.
  74315. this._loaderPendingCount = 0;
  74316. this._parent = parent;
  74317. }
  74318. GLTFLoader.RegisterExtension = function (extension) {
  74319. if (GLTFLoader.Extensions[extension.name]) {
  74320. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  74321. return;
  74322. }
  74323. GLTFLoader.Extensions[extension.name] = extension;
  74324. // Keep the order of registration so that extensions registered first are called first.
  74325. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  74326. };
  74327. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  74328. get: function () {
  74329. return this._gltf;
  74330. },
  74331. enumerable: true,
  74332. configurable: true
  74333. });
  74334. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  74335. get: function () {
  74336. return this._babylonScene;
  74337. },
  74338. enumerable: true,
  74339. configurable: true
  74340. });
  74341. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  74342. if (this._renderReady) {
  74343. func();
  74344. }
  74345. else {
  74346. this._renderReadyObservable.add(func);
  74347. }
  74348. };
  74349. GLTFLoader.prototype.dispose = function () {
  74350. if (this._disposed) {
  74351. return;
  74352. }
  74353. this._disposed = true;
  74354. // Revoke object urls created during load
  74355. if (this._gltf.textures) {
  74356. this._gltf.textures.forEach(function (texture) {
  74357. if (texture.url) {
  74358. URL.revokeObjectURL(texture.url);
  74359. }
  74360. });
  74361. }
  74362. this._gltf = undefined;
  74363. this._babylonScene = undefined;
  74364. this._rootUrl = undefined;
  74365. this._defaultMaterial = undefined;
  74366. this._successCallback = undefined;
  74367. this._errorCallback = undefined;
  74368. this._renderReady = false;
  74369. this._renderReadyObservable.clear();
  74370. this._renderPendingCount = 0;
  74371. this._loaderPendingCount = 0;
  74372. };
  74373. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74374. var _this = this;
  74375. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  74376. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  74377. }, onProgress, onError);
  74378. };
  74379. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74380. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  74381. };
  74382. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74383. this._loadData(data);
  74384. this._babylonScene = scene;
  74385. this._rootUrl = rootUrl;
  74386. this._successCallback = onSuccess;
  74387. this._progressCallback = onProgress;
  74388. this._errorCallback = onError;
  74389. this.addPendingData(this);
  74390. this._loadScene(nodeNames);
  74391. this._loadAnimations();
  74392. this.removePendingData(this);
  74393. };
  74394. GLTFLoader.prototype._onError = function (message) {
  74395. this._errorCallback(message);
  74396. this.dispose();
  74397. };
  74398. GLTFLoader.prototype._onProgress = function (event) {
  74399. this._progressCallback(event);
  74400. };
  74401. GLTFLoader.prototype._onRenderReady = function () {
  74402. switch (this._parent.coordinateSystemMode) {
  74403. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  74404. if (!this._babylonScene.useRightHandedSystem) {
  74405. this._addRightHandToLeftHandRootTransform();
  74406. }
  74407. break;
  74408. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  74409. // do nothing
  74410. break;
  74411. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  74412. this._babylonScene.useRightHandedSystem = true;
  74413. break;
  74414. default:
  74415. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  74416. break;
  74417. }
  74418. this._showMeshes();
  74419. this._startAnimations();
  74420. this._successCallback();
  74421. this._renderReadyObservable.notifyObservers(this);
  74422. };
  74423. GLTFLoader.prototype._onLoaderComplete = function () {
  74424. if (this._parent.onComplete) {
  74425. this._parent.onComplete();
  74426. }
  74427. };
  74428. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  74429. if (this._parent.onFirstLODComplete) {
  74430. this._parent.onFirstLODComplete();
  74431. }
  74432. };
  74433. GLTFLoader.prototype._loadData = function (data) {
  74434. this._gltf = data.json;
  74435. var binaryBuffer;
  74436. var buffers = this._gltf.buffers;
  74437. if (buffers && buffers[0].uri === undefined) {
  74438. binaryBuffer = buffers[0];
  74439. }
  74440. if (data.bin) {
  74441. if (binaryBuffer) {
  74442. if (binaryBuffer.byteLength != data.bin.byteLength) {
  74443. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  74444. }
  74445. }
  74446. else {
  74447. BABYLON.Tools.Warn("Unexpected BIN chunk");
  74448. }
  74449. binaryBuffer.loadedData = data.bin;
  74450. }
  74451. };
  74452. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  74453. this._rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  74454. this._rootMesh.isVisible = false;
  74455. this._rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  74456. this._rootMesh.rotation.y = Math.PI;
  74457. var nodes = this._gltf.nodes;
  74458. if (nodes) {
  74459. for (var i = 0; i < nodes.length; i++) {
  74460. var mesh = nodes[i].babylonMesh;
  74461. if (mesh && !mesh.parent) {
  74462. mesh.parent = this._rootMesh;
  74463. }
  74464. }
  74465. }
  74466. };
  74467. GLTFLoader.prototype._getMeshes = function () {
  74468. var meshes = [];
  74469. if (this._rootMesh) {
  74470. meshes.push(this._rootMesh);
  74471. }
  74472. var nodes = this._gltf.nodes;
  74473. if (nodes) {
  74474. nodes.forEach(function (node) {
  74475. if (node.babylonMesh) {
  74476. meshes.push(node.babylonMesh);
  74477. }
  74478. });
  74479. }
  74480. return meshes;
  74481. };
  74482. GLTFLoader.prototype._getSkeletons = function () {
  74483. var skeletons = [];
  74484. var skins = this._gltf.skins;
  74485. if (skins) {
  74486. skins.forEach(function (skin) {
  74487. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74488. skeletons.push(skin.babylonSkeleton);
  74489. }
  74490. });
  74491. }
  74492. return skeletons;
  74493. };
  74494. GLTFLoader.prototype._getAnimationTargets = function () {
  74495. var targets = [];
  74496. var animations = this._gltf.animations;
  74497. if (animations) {
  74498. animations.forEach(function (animation) {
  74499. targets.push.apply(targets, animation.targets);
  74500. });
  74501. }
  74502. return targets;
  74503. };
  74504. GLTFLoader.prototype._showMeshes = function () {
  74505. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  74506. };
  74507. GLTFLoader.prototype._startAnimations = function () {
  74508. var _this = this;
  74509. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  74510. };
  74511. GLTFLoader.prototype._loadScene = function (nodeNames) {
  74512. var _this = this;
  74513. var scene = this._gltf.scenes[this._gltf.scene || 0];
  74514. var nodeIndices = scene.nodes;
  74515. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  74516. node.index = index;
  74517. node.parent = parentNode;
  74518. return true;
  74519. });
  74520. var materials = this._gltf.materials;
  74521. if (materials) {
  74522. materials.forEach(function (material, index) { return material.index = index; });
  74523. }
  74524. if (nodeNames) {
  74525. if (!(nodeNames instanceof Array)) {
  74526. nodeNames = [nodeNames];
  74527. }
  74528. var filteredNodeIndices = new Array();
  74529. this._traverseNodes(nodeIndices, function (node) {
  74530. if (nodeNames.indexOf(node.name) === -1) {
  74531. return true;
  74532. }
  74533. filteredNodeIndices.push(node.index);
  74534. return false;
  74535. });
  74536. nodeIndices = filteredNodeIndices;
  74537. }
  74538. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  74539. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  74540. };
  74541. GLTFLoader.prototype._loadSkin = function (node) {
  74542. var _this = this;
  74543. if (node.skin !== undefined) {
  74544. var skin = this._gltf.skins[node.skin];
  74545. var skeletonId = "skeleton" + node.skin;
  74546. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  74547. skin.index = node.skin;
  74548. for (var i = 0; i < skin.joints.length; i++) {
  74549. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  74550. }
  74551. if (skin.skeleton === undefined) {
  74552. // TODO: handle when skeleton is not defined
  74553. throw new Error("Not implemented");
  74554. }
  74555. if (skin.inverseBindMatrices === undefined) {
  74556. // TODO: handle when inverse bind matrices are not defined
  74557. throw new Error("Not implemented");
  74558. }
  74559. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  74560. this._loadAccessorAsync(accessor, function (data) {
  74561. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  74562. });
  74563. }
  74564. return true;
  74565. };
  74566. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  74567. var jointIndex = skin.joints.indexOf(node.index);
  74568. if (jointIndex === -1) {
  74569. this._createBone(node, skin);
  74570. }
  74571. var babylonBone = node.babylonSkinToBones[skin.index];
  74572. // TODO: explain the math
  74573. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  74574. matrix.invertToRef(matrix);
  74575. if (parentNode) {
  74576. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  74577. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  74578. }
  74579. babylonBone.updateMatrix(matrix);
  74580. return true;
  74581. };
  74582. GLTFLoader.prototype._createBone = function (node, skin) {
  74583. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  74584. node.babylonSkinToBones = node.babylonSkinToBones || {};
  74585. node.babylonSkinToBones[skin.index] = babylonBone;
  74586. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74587. node.babylonAnimationTargets.push(babylonBone);
  74588. return babylonBone;
  74589. };
  74590. GLTFLoader.prototype._loadMesh = function (node) {
  74591. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  74592. babylonMesh.isVisible = false;
  74593. this._loadTransform(node, babylonMesh);
  74594. if (node.mesh !== undefined) {
  74595. var mesh = this._gltf.meshes[node.mesh];
  74596. this._loadMeshData(node, mesh, babylonMesh);
  74597. }
  74598. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  74599. node.babylonMesh = babylonMesh;
  74600. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74601. node.babylonAnimationTargets.push(node.babylonMesh);
  74602. if (node.skin !== undefined) {
  74603. var skin = this._gltf.skins[node.skin];
  74604. babylonMesh.skeleton = skin.babylonSkeleton;
  74605. }
  74606. if (node.camera !== undefined) {
  74607. // TODO: handle cameras
  74608. }
  74609. return true;
  74610. };
  74611. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  74612. var _this = this;
  74613. babylonMesh.name = mesh.name || babylonMesh.name;
  74614. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  74615. babylonMesh.material = babylonMultiMaterial;
  74616. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  74617. var vertexData = new BABYLON.VertexData();
  74618. vertexData.positions = [];
  74619. vertexData.indices = [];
  74620. var subMeshInfos = [];
  74621. var loadedPrimitives = 0;
  74622. var totalPrimitives = mesh.primitives.length;
  74623. var _loop_1 = function (i) {
  74624. var primitive = mesh.primitives[i];
  74625. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  74626. // TODO: handle other primitive modes
  74627. throw new Error("Not implemented");
  74628. }
  74629. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  74630. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  74631. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  74632. subMeshInfos.push({
  74633. materialIndex: i,
  74634. verticesStart: vertexData.positions.length,
  74635. verticesCount: subVertexData.positions.length,
  74636. indicesStart: vertexData.indices.length,
  74637. indicesCount: subVertexData.indices.length,
  74638. loadMaterial: function () {
  74639. if (primitive.material === undefined) {
  74640. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  74641. }
  74642. else {
  74643. var material = _this._gltf.materials[primitive.material];
  74644. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  74645. if (isNew && _this._parent.onMaterialLoaded) {
  74646. _this._parent.onMaterialLoaded(babylonMaterial);
  74647. }
  74648. if (_this._parent.onBeforeMaterialReadyAsync) {
  74649. _this.addLoaderPendingData(material);
  74650. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  74651. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74652. _this.removeLoaderPendingData(material);
  74653. });
  74654. }
  74655. else {
  74656. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74657. }
  74658. });
  74659. }
  74660. }
  74661. });
  74662. vertexData.merge(subVertexData);
  74663. if (++loadedPrimitives === totalPrimitives) {
  74664. geometry.setAllVerticesData(vertexData, false);
  74665. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  74666. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  74667. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  74668. babylonMesh.subMeshes = [];
  74669. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  74670. }
  74671. });
  74672. };
  74673. var this_1 = this;
  74674. for (var i = 0; i < totalPrimitives; i++) {
  74675. _loop_1(i);
  74676. }
  74677. };
  74678. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  74679. var _this = this;
  74680. var attributes = primitive.attributes;
  74681. if (!attributes) {
  74682. this._onError("Primitive has no attributes");
  74683. return;
  74684. }
  74685. var vertexData = new BABYLON.VertexData();
  74686. var loadedAttributes = 0;
  74687. var totalAttributes = Object.keys(attributes).length;
  74688. var _loop_2 = function (semantic) {
  74689. accessor = this_2._gltf.accessors[attributes[semantic]];
  74690. this_2._loadAccessorAsync(accessor, function (data) {
  74691. switch (semantic) {
  74692. case "NORMAL":
  74693. vertexData.normals = data;
  74694. break;
  74695. case "POSITION":
  74696. vertexData.positions = data;
  74697. break;
  74698. case "TANGENT":
  74699. vertexData.tangents = data;
  74700. break;
  74701. case "TEXCOORD_0":
  74702. vertexData.uvs = data;
  74703. break;
  74704. case "TEXCOORD_1":
  74705. vertexData.uvs2 = data;
  74706. break;
  74707. case "JOINTS_0":
  74708. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  74709. break;
  74710. case "WEIGHTS_0":
  74711. vertexData.matricesWeights = data;
  74712. break;
  74713. case "COLOR_0":
  74714. vertexData.colors = data;
  74715. break;
  74716. default:
  74717. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  74718. break;
  74719. }
  74720. if (++loadedAttributes === totalAttributes) {
  74721. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  74722. if (indicesAccessor) {
  74723. _this._loadAccessorAsync(indicesAccessor, function (data) {
  74724. vertexData.indices = data;
  74725. onSuccess(vertexData);
  74726. });
  74727. }
  74728. else {
  74729. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  74730. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  74731. onSuccess(vertexData);
  74732. }
  74733. }
  74734. });
  74735. };
  74736. var this_2 = this, accessor;
  74737. for (var semantic in attributes) {
  74738. _loop_2(semantic);
  74739. }
  74740. };
  74741. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  74742. var targets = primitive.targets;
  74743. if (!targets) {
  74744. return;
  74745. }
  74746. if (!babylonMesh.morphTargetManager) {
  74747. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  74748. }
  74749. for (var index = 0; index < targets.length; index++) {
  74750. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  74751. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  74752. }
  74753. };
  74754. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  74755. var targets = primitive.targets;
  74756. if (!targets) {
  74757. return;
  74758. }
  74759. var _loop_3 = function () {
  74760. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  74761. attributes = targets[index];
  74762. var _loop_4 = function (semantic) {
  74763. accessor = this_3._gltf.accessors[attributes[semantic]];
  74764. this_3._loadAccessorAsync(accessor, function (data) {
  74765. if (accessor.name) {
  74766. babylonMorphTarget.name = accessor.name;
  74767. }
  74768. // glTF stores morph target information as deltas while babylon.js expects the final data.
  74769. // As a result we have to add the original data to the delta to calculate the final data.
  74770. var values = data;
  74771. switch (semantic) {
  74772. case "NORMAL":
  74773. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  74774. babylonMorphTarget.setNormals(values);
  74775. break;
  74776. case "POSITION":
  74777. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  74778. babylonMorphTarget.setPositions(values);
  74779. break;
  74780. case "TANGENT":
  74781. // Tangent data for morph targets is stored as xyz delta.
  74782. // The vertexData.tangent is stored as xyzw.
  74783. // So we need to skip every fourth vertexData.tangent.
  74784. for (var i = 0, j = 0; i < values.length; i++, j++) {
  74785. values[i] += vertexData.tangents[j];
  74786. if ((i + 1) % 3 == 0) {
  74787. j++;
  74788. }
  74789. }
  74790. babylonMorphTarget.setTangents(values);
  74791. break;
  74792. default:
  74793. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  74794. break;
  74795. }
  74796. });
  74797. };
  74798. for (var semantic in attributes) {
  74799. _loop_4(semantic);
  74800. }
  74801. };
  74802. var this_3 = this, attributes, accessor;
  74803. for (var index = 0; index < targets.length; index++) {
  74804. _loop_3();
  74805. }
  74806. };
  74807. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  74808. var position = BABYLON.Vector3.Zero();
  74809. var rotation = BABYLON.Quaternion.Identity();
  74810. var scaling = BABYLON.Vector3.One();
  74811. if (node.matrix) {
  74812. var mat = BABYLON.Matrix.FromArray(node.matrix);
  74813. mat.decompose(scaling, rotation, position);
  74814. }
  74815. else {
  74816. if (node.translation)
  74817. position = BABYLON.Vector3.FromArray(node.translation);
  74818. if (node.rotation)
  74819. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  74820. if (node.scale)
  74821. scaling = BABYLON.Vector3.FromArray(node.scale);
  74822. }
  74823. babylonMesh.position = position;
  74824. babylonMesh.rotationQuaternion = rotation;
  74825. babylonMesh.scaling = scaling;
  74826. };
  74827. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  74828. if (parentNode === void 0) { parentNode = null; }
  74829. for (var i = 0; i < indices.length; i++) {
  74830. this._traverseNode(indices[i], action, parentNode);
  74831. }
  74832. };
  74833. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  74834. if (parentNode === void 0) { parentNode = null; }
  74835. var node = this._gltf.nodes[index];
  74836. if (!action(node, index, parentNode)) {
  74837. return;
  74838. }
  74839. if (node.children) {
  74840. for (var i = 0; i < node.children.length; i++) {
  74841. this._traverseNode(node.children[i], action, node);
  74842. }
  74843. }
  74844. };
  74845. GLTFLoader.prototype._loadAnimations = function () {
  74846. var animations = this._gltf.animations;
  74847. if (!animations || animations.length === 0) {
  74848. return;
  74849. }
  74850. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  74851. var animation = animations[animationIndex];
  74852. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  74853. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  74854. }
  74855. }
  74856. };
  74857. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  74858. var channel = animation.channels[channelIndex];
  74859. var samplerIndex = channel.sampler;
  74860. var sampler = animation.samplers[samplerIndex];
  74861. var targetNode = this._gltf.nodes[channel.target.node];
  74862. if (!targetNode) {
  74863. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  74864. return;
  74865. }
  74866. var targetPath = {
  74867. "translation": "position",
  74868. "rotation": "rotationQuaternion",
  74869. "scale": "scaling",
  74870. "weights": "influence"
  74871. }[channel.target.path];
  74872. if (!targetPath) {
  74873. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  74874. return;
  74875. }
  74876. var animationType = {
  74877. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  74878. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  74879. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  74880. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  74881. }[targetPath];
  74882. var inputData;
  74883. var outputData;
  74884. var checkSuccess = function () {
  74885. if (!inputData || !outputData) {
  74886. return;
  74887. }
  74888. var outputBufferOffset = 0;
  74889. var getNextOutputValue = {
  74890. "position": function () {
  74891. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  74892. outputBufferOffset += 3;
  74893. return value;
  74894. },
  74895. "rotationQuaternion": function () {
  74896. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  74897. outputBufferOffset += 4;
  74898. return value;
  74899. },
  74900. "scaling": function () {
  74901. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  74902. outputBufferOffset += 3;
  74903. return value;
  74904. },
  74905. "influence": function () {
  74906. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  74907. var value = new Array(numTargets);
  74908. for (var i = 0; i < numTargets; i++) {
  74909. value[i] = outputData[outputBufferOffset++];
  74910. }
  74911. return value;
  74912. },
  74913. }[targetPath];
  74914. var getNextKey = {
  74915. "LINEAR": function (frameIndex) { return ({
  74916. frame: inputData[frameIndex],
  74917. value: getNextOutputValue()
  74918. }); },
  74919. "CUBICSPLINE": function (frameIndex) { return ({
  74920. frame: inputData[frameIndex],
  74921. inTangent: getNextOutputValue(),
  74922. value: getNextOutputValue(),
  74923. outTangent: getNextOutputValue()
  74924. }); },
  74925. }[sampler.interpolation];
  74926. var keys = new Array(inputData.length);
  74927. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  74928. keys[frameIndex] = getNextKey(frameIndex);
  74929. }
  74930. animation.targets = animation.targets || [];
  74931. if (targetPath === "influence") {
  74932. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  74933. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  74934. var morphTarget = morphTargetManager.getTarget(targetIndex);
  74935. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  74936. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  74937. babylonAnimation.setKeys(keys.map(function (key) { return ({
  74938. frame: key.frame,
  74939. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  74940. value: key.value[targetIndex],
  74941. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  74942. }); }));
  74943. morphTarget.animations.push(babylonAnimation);
  74944. animation.targets.push(morphTarget);
  74945. }
  74946. }
  74947. else {
  74948. var animationName = animation.name || "anim" + animationIndex;
  74949. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  74950. babylonAnimation.setKeys(keys);
  74951. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  74952. var target = targetNode.babylonAnimationTargets[i];
  74953. target.animations.push(babylonAnimation.clone());
  74954. animation.targets.push(target);
  74955. }
  74956. }
  74957. };
  74958. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  74959. inputData = data;
  74960. checkSuccess();
  74961. });
  74962. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  74963. outputData = data;
  74964. checkSuccess();
  74965. });
  74966. };
  74967. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  74968. var _this = this;
  74969. var buffer = this._gltf.buffers[index];
  74970. this.addPendingData(buffer);
  74971. if (buffer.loadedData) {
  74972. setTimeout(function () {
  74973. onSuccess(buffer.loadedData);
  74974. _this.removePendingData(buffer);
  74975. });
  74976. }
  74977. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  74978. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  74979. buffer.loadedData = new Uint8Array(data);
  74980. setTimeout(function () {
  74981. onSuccess(buffer.loadedData);
  74982. _this.removePendingData(buffer);
  74983. });
  74984. }
  74985. else if (buffer.loadedObservable) {
  74986. buffer.loadedObservable.add(function (buffer) {
  74987. onSuccess(buffer.loadedData);
  74988. _this.removePendingData(buffer);
  74989. });
  74990. }
  74991. else {
  74992. buffer.loadedObservable = new BABYLON.Observable();
  74993. buffer.loadedObservable.add(function (buffer) {
  74994. onSuccess(buffer.loadedData);
  74995. _this.removePendingData(buffer);
  74996. });
  74997. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  74998. buffer.loadedData = new Uint8Array(data);
  74999. buffer.loadedObservable.notifyObservers(buffer);
  75000. buffer.loadedObservable = null;
  75001. }, function (event) {
  75002. if (!_this._disposed) {
  75003. _this._onProgress(event);
  75004. }
  75005. }, this._babylonScene.database, true, function (request) {
  75006. if (!_this._disposed) {
  75007. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  75008. _this.removePendingData(buffer);
  75009. }
  75010. });
  75011. }
  75012. };
  75013. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75014. if (!byteStride) {
  75015. return new Int8Array(buffer, byteOffset, byteLength);
  75016. }
  75017. var sourceBuffer = new Int8Array(buffer, byteOffset);
  75018. var targetBuffer = new Int8Array(byteLength);
  75019. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75020. return targetBuffer;
  75021. };
  75022. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75023. if (!byteStride) {
  75024. return new Uint8Array(buffer, byteOffset, byteLength);
  75025. }
  75026. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  75027. var targetBuffer = new Uint8Array(byteLength);
  75028. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  75029. return targetBuffer;
  75030. };
  75031. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75032. if (!byteStride) {
  75033. return new Int16Array(buffer, byteOffset, byteLength);
  75034. }
  75035. var sourceBuffer = new Int16Array(buffer, byteOffset);
  75036. var targetBuffer = new Int16Array(byteLength);
  75037. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75038. return targetBuffer;
  75039. };
  75040. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75041. if (!byteStride) {
  75042. return new Uint16Array(buffer, byteOffset, byteLength);
  75043. }
  75044. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  75045. var targetBuffer = new Uint16Array(byteLength);
  75046. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  75047. return targetBuffer;
  75048. };
  75049. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75050. if (!byteStride) {
  75051. return new Uint32Array(buffer, byteOffset, byteLength);
  75052. }
  75053. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  75054. var targetBuffer = new Uint32Array(byteLength);
  75055. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75056. return targetBuffer;
  75057. };
  75058. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  75059. if (!byteStride) {
  75060. return new Float32Array(buffer, byteOffset, byteLength);
  75061. }
  75062. var sourceBuffer = new Float32Array(buffer, byteOffset);
  75063. var targetBuffer = new Float32Array(byteLength);
  75064. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  75065. return targetBuffer;
  75066. };
  75067. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  75068. var tempIndex = 0;
  75069. var sourceIndex = 0;
  75070. var storageSize = bytePerComponent;
  75071. while (tempIndex < length) {
  75072. for (var cursor = 0; cursor < storageSize; cursor++) {
  75073. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  75074. tempIndex++;
  75075. }
  75076. sourceIndex += stride;
  75077. }
  75078. };
  75079. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  75080. var _this = this;
  75081. byteOffset += (bufferView.byteOffset || 0);
  75082. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  75083. if (byteOffset + byteLength > bufferData.byteLength) {
  75084. _this._onError("Buffer access is out of range");
  75085. return;
  75086. }
  75087. var buffer = bufferData.buffer;
  75088. byteOffset += bufferData.byteOffset;
  75089. var bufferViewData;
  75090. switch (componentType) {
  75091. case GLTF2.EComponentType.BYTE:
  75092. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75093. break;
  75094. case GLTF2.EComponentType.UNSIGNED_BYTE:
  75095. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75096. break;
  75097. case GLTF2.EComponentType.SHORT:
  75098. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75099. break;
  75100. case GLTF2.EComponentType.UNSIGNED_SHORT:
  75101. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75102. break;
  75103. case GLTF2.EComponentType.UNSIGNED_INT:
  75104. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75105. break;
  75106. case GLTF2.EComponentType.FLOAT:
  75107. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  75108. break;
  75109. default:
  75110. _this._onError("Invalid component type (" + componentType + ")");
  75111. return;
  75112. }
  75113. onSuccess(bufferViewData);
  75114. });
  75115. };
  75116. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  75117. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  75118. var byteOffset = accessor.byteOffset || 0;
  75119. var bytePerComponent = this._getByteStrideFromType(accessor);
  75120. var byteLength = accessor.count * bytePerComponent;
  75121. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  75122. };
  75123. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  75124. switch (accessor.type) {
  75125. case "SCALAR": return 1;
  75126. case "VEC2": return 2;
  75127. case "VEC3": return 3;
  75128. case "VEC4": return 4;
  75129. case "MAT2": return 4;
  75130. case "MAT3": return 9;
  75131. case "MAT4": return 16;
  75132. default:
  75133. this._onError("Invalid accessor type (" + accessor.type + ")");
  75134. return 0;
  75135. }
  75136. };
  75137. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  75138. set: function (value) {
  75139. this._blockPendingTracking = value;
  75140. },
  75141. enumerable: true,
  75142. configurable: true
  75143. });
  75144. GLTFLoader.prototype.addPendingData = function (data) {
  75145. if (!this._renderReady) {
  75146. this._renderPendingCount++;
  75147. }
  75148. this.addLoaderPendingData(data);
  75149. };
  75150. GLTFLoader.prototype.removePendingData = function (data) {
  75151. if (!this._renderReady) {
  75152. if (--this._renderPendingCount === 0) {
  75153. this._renderReady = true;
  75154. this._onRenderReady();
  75155. }
  75156. }
  75157. this.removeLoaderPendingData(data);
  75158. };
  75159. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  75160. if (!this._nonBlockingData) {
  75161. this._nonBlockingData = new Array();
  75162. }
  75163. this._nonBlockingData.push(data);
  75164. };
  75165. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  75166. if (this._blockPendingTracking) {
  75167. this.addLoaderNonBlockingPendingData(data);
  75168. return;
  75169. }
  75170. this._loaderPendingCount++;
  75171. };
  75172. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  75173. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  75174. if (indexInPending !== -1) {
  75175. this._nonBlockingData.splice(indexInPending, 1);
  75176. }
  75177. else if (--this._loaderPendingCount === 0) {
  75178. this._onLoaderFirstLODComplete();
  75179. }
  75180. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  75181. this._onLoaderComplete();
  75182. this.dispose();
  75183. }
  75184. };
  75185. GLTFLoader.prototype._getDefaultMaterial = function () {
  75186. if (!this._defaultMaterial) {
  75187. var id = "__gltf_default";
  75188. var material = this._babylonScene.getMaterialByName(id);
  75189. if (!material) {
  75190. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  75191. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75192. material.metallic = 1;
  75193. material.roughness = 1;
  75194. }
  75195. this._defaultMaterial = material;
  75196. }
  75197. return this._defaultMaterial;
  75198. };
  75199. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  75200. var babylonMaterial = material.babylonMaterial;
  75201. // Ensure metallic workflow
  75202. babylonMaterial.metallic = 1;
  75203. babylonMaterial.roughness = 1;
  75204. var properties = material.pbrMetallicRoughness;
  75205. if (!properties) {
  75206. return;
  75207. }
  75208. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  75209. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  75210. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  75211. if (properties.baseColorTexture) {
  75212. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  75213. }
  75214. if (properties.metallicRoughnessTexture) {
  75215. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  75216. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  75217. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  75218. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  75219. }
  75220. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  75221. };
  75222. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  75223. if (material.babylonMaterial) {
  75224. assign(material.babylonMaterial, false);
  75225. return;
  75226. }
  75227. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  75228. return;
  75229. }
  75230. this.createPbrMaterial(material);
  75231. this.loadMaterialBaseProperties(material);
  75232. this._loadMaterialMetallicRoughnessProperties(material);
  75233. assign(material.babylonMaterial, true);
  75234. };
  75235. GLTFLoader.prototype.createPbrMaterial = function (material) {
  75236. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  75237. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75238. material.babylonMaterial = babylonMaterial;
  75239. };
  75240. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  75241. var babylonMaterial = material.babylonMaterial;
  75242. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  75243. if (material.doubleSided) {
  75244. babylonMaterial.backFaceCulling = false;
  75245. babylonMaterial.twoSidedLighting = true;
  75246. }
  75247. if (material.normalTexture) {
  75248. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  75249. babylonMaterial.invertNormalMapX = true;
  75250. babylonMaterial.invertNormalMapY = false;
  75251. if (material.normalTexture.scale !== undefined) {
  75252. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  75253. }
  75254. }
  75255. if (material.occlusionTexture) {
  75256. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  75257. babylonMaterial.useAmbientInGrayScale = true;
  75258. if (material.occlusionTexture.strength !== undefined) {
  75259. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  75260. }
  75261. }
  75262. if (material.emissiveTexture) {
  75263. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  75264. }
  75265. };
  75266. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  75267. var babylonMaterial = material.babylonMaterial;
  75268. var alphaMode = material.alphaMode || "OPAQUE";
  75269. switch (alphaMode) {
  75270. case "OPAQUE":
  75271. // default is opaque
  75272. break;
  75273. case "MASK":
  75274. case "BLEND":
  75275. if (colorFactor) {
  75276. babylonMaterial.alpha = colorFactor[3];
  75277. }
  75278. if (babylonMaterial.albedoTexture) {
  75279. babylonMaterial.albedoTexture.hasAlpha = true;
  75280. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  75281. }
  75282. break;
  75283. default:
  75284. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  75285. break;
  75286. }
  75287. babylonMaterial.alphaCutOff = material.alphaCutoff === undefined ? 0.5 : material.alphaCutoff;
  75288. };
  75289. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  75290. var _this = this;
  75291. var texture = this._gltf.textures[textureInfo.index];
  75292. var texCoord = textureInfo.texCoord || 0;
  75293. if (!texture || texture.source === undefined) {
  75294. return null;
  75295. }
  75296. var source = this._gltf.images[texture.source];
  75297. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  75298. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  75299. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  75300. this.addPendingData(texture);
  75301. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  75302. if (!_this._disposed) {
  75303. _this.removePendingData(texture);
  75304. }
  75305. }, function () {
  75306. if (!_this._disposed) {
  75307. _this._onError("Failed to load texture '" + source.uri + "'");
  75308. _this.removePendingData(texture);
  75309. }
  75310. });
  75311. if (texture.url) {
  75312. babylonTexture.updateURL(texture.url);
  75313. }
  75314. else if (texture.dataReadyObservable) {
  75315. texture.dataReadyObservable.add(function (texture) {
  75316. babylonTexture.updateURL(texture.url);
  75317. });
  75318. }
  75319. else {
  75320. texture.dataReadyObservable = new BABYLON.Observable();
  75321. texture.dataReadyObservable.add(function (texture) {
  75322. babylonTexture.updateURL(texture.url);
  75323. });
  75324. var setTextureData = function (data) {
  75325. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  75326. texture.dataReadyObservable.notifyObservers(texture);
  75327. };
  75328. if (!source.uri) {
  75329. var bufferView = this._gltf.bufferViews[source.bufferView];
  75330. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  75331. }
  75332. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  75333. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  75334. }
  75335. else {
  75336. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  75337. if (!_this._disposed) {
  75338. _this._onProgress(event);
  75339. }
  75340. }, this._babylonScene.database, true, function (request) {
  75341. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  75342. });
  75343. }
  75344. }
  75345. babylonTexture.coordinatesIndex = texCoord;
  75346. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  75347. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  75348. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  75349. if (this._parent.onTextureLoaded) {
  75350. this._parent.onTextureLoaded(babylonTexture);
  75351. }
  75352. return babylonTexture;
  75353. };
  75354. GLTFLoader.Extensions = {};
  75355. return GLTFLoader;
  75356. }());
  75357. GLTF2.GLTFLoader = GLTFLoader;
  75358. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  75359. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75360. })(BABYLON || (BABYLON = {}));
  75361. //# sourceMappingURL=babylon.glTFLoader.js.map
  75362. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75363. var BABYLON;
  75364. (function (BABYLON) {
  75365. var GLTF2;
  75366. (function (GLTF2) {
  75367. /**
  75368. * Utils functions for GLTF
  75369. */
  75370. var GLTFUtils = (function () {
  75371. function GLTFUtils() {
  75372. }
  75373. /**
  75374. * If the uri is a base64 string
  75375. * @param uri: the uri to test
  75376. */
  75377. GLTFUtils.IsBase64 = function (uri) {
  75378. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  75379. };
  75380. /**
  75381. * Decode the base64 uri
  75382. * @param uri: the uri to decode
  75383. */
  75384. GLTFUtils.DecodeBase64 = function (uri) {
  75385. var decodedString = atob(uri.split(",")[1]);
  75386. var bufferLength = decodedString.length;
  75387. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  75388. for (var i = 0; i < bufferLength; i++) {
  75389. bufferView[i] = decodedString.charCodeAt(i);
  75390. }
  75391. return bufferView.buffer;
  75392. };
  75393. GLTFUtils.ForEach = function (view, func) {
  75394. for (var index = 0; index < view.length; index++) {
  75395. func(view[index], index);
  75396. }
  75397. };
  75398. GLTFUtils.GetTextureWrapMode = function (mode) {
  75399. // Set defaults if undefined
  75400. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  75401. switch (mode) {
  75402. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  75403. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  75404. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  75405. default:
  75406. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  75407. return BABYLON.Texture.WRAP_ADDRESSMODE;
  75408. }
  75409. };
  75410. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  75411. // Set defaults if undefined
  75412. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  75413. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  75414. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  75415. switch (minFilter) {
  75416. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  75417. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  75418. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  75419. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  75420. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  75421. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  75422. default:
  75423. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  75424. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  75425. }
  75426. }
  75427. else {
  75428. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  75429. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  75430. }
  75431. switch (minFilter) {
  75432. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  75433. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  75434. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  75435. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  75436. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  75437. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  75438. default:
  75439. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  75440. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  75441. }
  75442. }
  75443. };
  75444. /**
  75445. * Decodes a buffer view into a string
  75446. * @param view: the buffer view
  75447. */
  75448. GLTFUtils.DecodeBufferToText = function (view) {
  75449. var result = "";
  75450. var length = view.byteLength;
  75451. for (var i = 0; i < length; ++i) {
  75452. result += String.fromCharCode(view[i]);
  75453. }
  75454. return result;
  75455. };
  75456. return GLTFUtils;
  75457. }());
  75458. GLTF2.GLTFUtils = GLTFUtils;
  75459. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75460. })(BABYLON || (BABYLON = {}));
  75461. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  75462. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75463. var BABYLON;
  75464. (function (BABYLON) {
  75465. var GLTF2;
  75466. (function (GLTF2) {
  75467. var GLTFLoaderExtension = (function () {
  75468. function GLTFLoaderExtension() {
  75469. this.enabled = true;
  75470. }
  75471. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  75472. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  75473. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  75474. };
  75475. GLTFLoaderExtension._ApplyExtensions = function (action) {
  75476. var extensions = GLTFLoaderExtension._Extensions;
  75477. if (!extensions) {
  75478. return;
  75479. }
  75480. for (var i = 0; i < extensions.length; i++) {
  75481. var extension = extensions[i];
  75482. if (extension.enabled && action(extension)) {
  75483. return true;
  75484. }
  75485. }
  75486. return false;
  75487. };
  75488. //
  75489. // Utilities
  75490. //
  75491. GLTFLoaderExtension._Extensions = [];
  75492. return GLTFLoaderExtension;
  75493. }());
  75494. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  75495. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75496. })(BABYLON || (BABYLON = {}));
  75497. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  75498. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75499. var BABYLON;
  75500. (function (BABYLON) {
  75501. var GLTF2;
  75502. (function (GLTF2) {
  75503. var Extensions;
  75504. (function (Extensions) {
  75505. var MSFTLOD = (function (_super) {
  75506. __extends(MSFTLOD, _super);
  75507. function MSFTLOD() {
  75508. return _super !== null && _super.apply(this, arguments) || this;
  75509. }
  75510. Object.defineProperty(MSFTLOD.prototype, "name", {
  75511. get: function () {
  75512. return "MSFT_lod";
  75513. },
  75514. enumerable: true,
  75515. configurable: true
  75516. });
  75517. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  75518. if (!material.extensions) {
  75519. return false;
  75520. }
  75521. var properties = material.extensions[this.name];
  75522. if (!properties) {
  75523. return false;
  75524. }
  75525. // Clear out the extension so that it won't get loaded again.
  75526. material.extensions[this.name] = undefined;
  75527. // Tell the loader not to clear its state until the highest LOD is loaded.
  75528. var materialLODs = [material.index].concat(properties.ids);
  75529. loader.addLoaderPendingData(material);
  75530. for (var index = 0; index < materialLODs.length; index++) {
  75531. loader.addLoaderNonBlockingPendingData(index);
  75532. }
  75533. // Start with the lowest quality LOD.
  75534. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  75535. return true;
  75536. };
  75537. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  75538. var _this = this;
  75539. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  75540. if (lod !== materialLODs.length - 1) {
  75541. loader.blockPendingTracking = true;
  75542. }
  75543. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  75544. assign(babylonMaterial, isNew);
  75545. loader.removeLoaderPendingData(lod);
  75546. // Loading is considered complete if this is the lowest quality LOD.
  75547. if (lod === materialLODs.length - 1) {
  75548. loader.removeLoaderPendingData(material);
  75549. }
  75550. if (lod === 0) {
  75551. loader.blockPendingTracking = false;
  75552. return;
  75553. }
  75554. // Load the next LOD when the loader is ready to render and
  75555. // all active material textures of the current LOD are loaded.
  75556. loader.executeWhenRenderReady(function () {
  75557. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  75558. setTimeout(function () {
  75559. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  75560. }, MSFTLOD.MinimalLODDelay);
  75561. });
  75562. });
  75563. });
  75564. };
  75565. /**
  75566. * Specify the minimal delay between LODs in ms (default = 250)
  75567. */
  75568. MSFTLOD.MinimalLODDelay = 250;
  75569. return MSFTLOD;
  75570. }(GLTF2.GLTFLoaderExtension));
  75571. Extensions.MSFTLOD = MSFTLOD;
  75572. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  75573. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75574. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75575. })(BABYLON || (BABYLON = {}));
  75576. //# sourceMappingURL=MSFT_lod.js.map
  75577. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75578. var BABYLON;
  75579. (function (BABYLON) {
  75580. var GLTF2;
  75581. (function (GLTF2) {
  75582. var Extensions;
  75583. (function (Extensions) {
  75584. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  75585. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  75586. function KHRMaterialsPbrSpecularGlossiness() {
  75587. return _super !== null && _super.apply(this, arguments) || this;
  75588. }
  75589. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  75590. get: function () {
  75591. return "KHR_materials_pbrSpecularGlossiness";
  75592. },
  75593. enumerable: true,
  75594. configurable: true
  75595. });
  75596. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  75597. if (!material.extensions) {
  75598. return false;
  75599. }
  75600. var properties = material.extensions[this.name];
  75601. if (!properties) {
  75602. return false;
  75603. }
  75604. loader.createPbrMaterial(material);
  75605. loader.loadMaterialBaseProperties(material);
  75606. this._loadSpecularGlossinessProperties(loader, material, properties);
  75607. assign(material.babylonMaterial, true);
  75608. return true;
  75609. };
  75610. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  75611. var babylonMaterial = material.babylonMaterial;
  75612. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  75613. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  75614. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  75615. if (properties.diffuseTexture) {
  75616. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  75617. }
  75618. if (properties.specularGlossinessTexture) {
  75619. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  75620. babylonMaterial.reflectivityTexture.hasAlpha = true;
  75621. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  75622. }
  75623. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  75624. };
  75625. return KHRMaterialsPbrSpecularGlossiness;
  75626. }(GLTF2.GLTFLoaderExtension));
  75627. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  75628. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  75629. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75630. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75631. })(BABYLON || (BABYLON = {}));
  75632. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  75633. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  75634. module.exports = BABYLON;
  75635. };